C++函数返回值为对象时构造析构函数的执行细节

2016-02-19 11:12 19 1 收藏

每个人都希望每天都是开心的,不要因为一些琐事扰乱了心情还,闲暇的时间怎么打发,关注图老师可以让你学习更多的好东西,下面为大家推荐C++函数返回值为对象时构造析构函数的执行细节,赶紧看过来吧!

【 tulaoshi.com - 编程语言 】

看如下代码:
代码如下:

#includeiostream
class TestConstructor
{
public:
    TestConstructor()
    {
        std::cout"TestConstructor()"std::endl;
    }
    ~TestConstructor()
    {
        std::cout"~TestConstructor()"std::endl;
    }
    TestConstructor(const TestConstructor& testObj)
    {
        std::cout"TestConstructor(const TestConstructor&)"std::endl;
    }
    TestConstructor& operator = (const TestConstructor& testObj)
    {
        std::cout"TestConstructor& operator = (const TestConstructor& testObj)"std::endl;
        return *this;
    }
};
TestConstructor testFunc()
{
    TestConstructor testInFunc;  //3、调用TestConstructor() 生成对象testInFunc
    return testInFunc;           //4、调用TestConstructor(const TestConstructor&) 生成临时对象
                                 //5、调用析构函数,析构对象testInFunc
}
int main()
{
    TestConstructor test;  //1、调用TestConstructor() 生成对象test
    test = testFunc();     //2、调用testFunc()    //6、调用等号把临时对象复制给对象test  //7、调用析构函数,析构临时对象
    return 0;              //8、调用析构函数,析构对象test
}

看输出:

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/bianchengyuyan/)

有注释,有输出。执行细节,一目了然了吧

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/bianchengyuyan/)

来源:https://www.tulaoshi.com/n/20160219/1596759.html

延伸阅读
在有两种情况下会调用析构函数。第一种是在正常情况下删除一个对象,例如对象超出了作用域或被显式地delete。第二种是异常传递的堆栈辗转开解(stack-unwinding)过程中,由异常处理系统删除一个对象。 在上述两种情况下,调用析构函数时异常可能处于激活状态也可能没有处于激活状态。遗憾的是没有办法在析构函数内部区分出这两...
析构函数的奥秘 作者:王咏武 提交者:eastvc 发布日期:2003-7-12 20:02:45 原文出处:http://www.contextfree.net/wangyw/deconstr.htm 请看如下一段代码: class A { public: A () { pValue = new int[100]; printf("Constructor of A\n"); } ~A () { delete [] pValue; printf("Deconstructor of A\n"); } priv...
在完整描述思想之前,我们先看一下如下的例子,这个例子中的加运算符重载是以非成员函数的方式出现的: !-- frame contents -- !-- /frame contents -- //程序作者:管宁  //站点:www.cndev-lab.com  //所有稿件均有版权,如要转载,请务必闻名出处和作者    #include iostream  ...
c++中,如果没有为一个类提供析构函数,那么编译器会为这个类提供默认的析构的函数。由于析构函数的功能和构造函数相反,因此和默认的构造函数类似,编译器也会提供无用的默认的析构函数,和非无用的析构函数。两者的分析情况一样(对于默认的构造函数分析,请参看《从汇编看c++中默认构造函数的使用分析》)。并且编译器会提供非无用的默认析构...
C++类对象的复制-拷贝构造函数(深拷贝,浅拷贝),进一步理解类成员的操作! 在学习这一章内容前我们已经学习过了类的构造函数和析构函数的相关知识,对于普通类型的对象来说,他们之间的复制是很简单的,例如: int a = 10; int b =a; 自己定义的类的对象同样是对象,谁也不能阻止我们用以下的方式进行复制,例如: //程序作者:管宁 ...

经验教程

847

收藏

41
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部