拷贝构造函数调用次数(函数的返回值是类对象的时候)

先看代码:

#include "stdafx.h"
#include<iostream>
using namespace std;
class CExample
{
private:
    int a;
public:
    //构造函数
    CExample(int b)
    {
        a=b;
        printf("constructor is called\n");
    }
    //拷贝构造函数
    CExample(const CExample & c)
    {
        a=c.a;
        printf("copy constructor is called\n");
    }
    //析构函数
    ~CExample()
    {
        cout<<"destructor is called\n";
    }
    void Show()
    {
        cout<<a<<endl;
    }
};

CExample g_fun()
{
    CExample temp(0);
    return temp;
}
int main()
{
    {
        CExample tt = g_fun();
    }
    getchar();
    return 0;
}

输出结果:


image.png

如果用下面的代码:

int main()
{
    {
        g_fun();
    }
    getchar();
    return 0;
}

输出结果:


image.png

疑问:为什么都是调用两遍析构函数,前面那个不是调用两遍拷贝构造函数,而是只调用一遍。析构函数也只是调用两遍?

之前我以为 return temp; 这句会调用一次拷贝构造函数,CExample tt =这句也会调用一次拷贝构造函数。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容