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

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

作者: 太平小小草 | 来源:发表于2018-11-04 19:59 被阅读0次

    先看代码:

    #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 =这句也会调用一次拷贝构造函数。

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/gijdxqtx.html