为什么不调用拷贝构造函数?

重载+号运算符代码中是返回的一个临时对象,按理说会调用一次拷贝,为什么没调用?

代码如下:

#include <iostream>
using namespace std;
class test
{
    friend test operator+(test& a);

public:
    //拷贝构造函数
    test(const test& t){
        cout<<"拷贝构造函数执行"<<endl;
        this->value=t.value;
        
    }
    
    //移动拷贝构造函数
    test(const test&& t){
        cout<<"移动拷贝构造函数执行"<<endl;
        this->value=t.value;
    }
    
    explicit test(int v){
        cout<<"构造函数执行"<<v<<endl;
        this->value=v;
    }
    
    ~test(){
        cout<<"析构函数执行"<<this->value<<endl;
    }

    
    test operator+(test& a){
        int tmp = a.value + this->value;
        test t(tmp);
        return t;
    }
    

    int getValue(){
        return this->value;
    }
private:
    int value;
    

};

int main()
{
    test t1(4);
    test t2(5);
    test t3 = t1+t2;
    
    cout<<t3.getValue()<<endl;
    
    return 0;
}

程序输出:

构造函数执行4
构造函数执行5
构造函数执行9
9
析构函数执行9
析构函数执行5
析构函数执行4

阅读 1.9k
1 个回答
//0930_copyConstructor
#include <iostream>
using namespace std;
class test
{
    //friend test operator+(test& a);

public:
    //拷贝构造函数
    test(const test& t){
        
        this->value=t.value;
        cout<<"copy constructor"<<value<<endl;
        
    }
    
    // //移动拷贝构造函数
    // test(const test&& t){
    //     cout<<"移动拷贝构造函数执行"<<endl;
    //     this->value=t.value;
    // }
    
    test(int v){
       
        this->value=v;
         cout<<"constructor"<<value<<endl;
    }
    
    ~test(){
        cout<<"~test()"<<value<<endl;
    }

    
    
    

    int getValue(){
        return this->value;
    }
private:
    int value;
    

};

test operator+(test a,test b){
        int tmp = a.getValue() + b.getValue();
        test t(tmp);
        cout<<"tmp constructed!"<<endl;
        cout<<&t<<endl;
        return t;
    }
test f(test a)
{
    return a;
}

int main()
{
    test t1(4);
    test t2(5);
    test t3 = t1+t2;
    cout<<&t3<<endl;
    
    cout<<t3.getValue()<<endl;
    test t4 = f(t1);
    return 0;
}

输出是
constructor4
constructor5
copy constructor5
copy constructor4
constructor9
tmp constructed!
0x28ff08
~test()4
~test()5
0x28ff08
9
copy constructor4
copy constructor4
~test()4
~test()4
~test()9
~test()5
~test()4

编译器进行了优化

可以看出t的地址和t3的地址是相同的,也就是说没有进行拷贝构造
我加了一个f(),其中参数x是拷贝构造过来的,编译器不会将这个参数直接放到t4的地址上,因此此处调用了拷贝构造函数。
而在operator+()中,编译时是可以发现t构造出了之后直接赋给t3,因此进行了优化。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题