码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-05-06 01:20:03      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

看如下代码:

复制代码代码如下:

#include<iostream>
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
}


看输出:

 

技术分享

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

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

标签:

原文地址:http://www.cnblogs.com/YiShuYuMengXiang/p/4480631.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!