简体   繁体   中英

What does a copy constructor actually do?

I am new to c++ programming and I am stuck at a part where both the members show the same value.. Can you guys explain why? Thx in advance.

#include<iostream>

using namespace std;

class test{
  public:
    int all,sum;

    test(int x){
        all=x;
    }

    test(test &a){
        all=a.all+5;
        cout<<all;   
    }

    void one(test m){
        cout<<endl;
        cout<<endl<<m.all;
        cout<<endl<<all;
    }
};

int main(){
    test a(10),b(a);
    b.one(a);
    return 0;
}

The problem is not that both a and b have the same value. Because they don't. A debugger would have shown you that a.all is 10 and b.all is 15, as expected.

The real problem is that you are passing a to one() by value , so the compiler has to make a temporary copy of a . That means the compiler will copy-construct m using your copy constructor (and will destroy m when one() exits). As such, the m.all value is always an incremented-by-5 value, never the original value.

In your example, the value of b.all and m.all just happen to be the same value, only because they are both copy-constructed from the same a object. Try passing b to one() instead ( b.one(b); ) and you will see that m.all will be 20 instead of 15.

To solve your issue, you need to change one() to take its m parameter by reference instead:

void one(const test &m) {
    cout<<endl;
    cout<<endl<<m.all;
    cout<<endl<<all;
}

That way, no temporary copy is needed. Passing a to one() will output a.all as-is, as expected. Passing b to one() will output b.all as-is, as expected. And so on.


Also, on a side note, your copy constructor should be taking its a parameter by const reference as well:

test(const test &a){
    all=a.all+5;
    cout<<all;   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM