简体   繁体   中英

C++ reference return of class object-why copy constructor not called?

Consider the following code dealing with reference return:

class Test  
{  
    public:  
    int data;

    Test() { data = 0; }
    Test(int u) { data = u;}

    Test& myfunction ();// function returning reference
    Test(Test& b) // copy constructor
    {
    cout<<"consructor called";
    }

    void print() { cout << data<<endl; }
};  
Test m(97);
Test& Test:: myfunction ()
{
    return m;
};    

int main()
{   Test a;
    Test b;
    b=a.myfunction();// why copy constructor not called?

    b.print();
    m.data=5;
    b.print();// if b is a reference of m then why its value not changed?

    return 0;
}

i hav two problem
1) is 'b' becomes reference of 'm' through following:

    b=a.myfunction();

if so then why its value not changed when value of 'm' is changed in

m.data=5;  

2) is ba normal object? . if so then why copy constructor is not called when following code is executed

b=a.myfunction();

the above code compiles fine with the following output:
97
5

Test b;

You just constructed the b object, using Test 's default constructor. Nothing you do will somehow magically "reconstruct" b . Everything you do with b now is being done on an already-constructed b .

b=a.myfunction();// why copy constructor not called?

The copy constructor isn't called because nothing is being constructed . Since you're assigning something to an already-constructed object, the object's copy assignment operator ( operator= ) is called.

Now if you want to ensure the copy constructor is called, you should do this instead:

Test b = a.myfunction();

is 'b' becomes reference of 'm'

No. You already declared b to be a Test object. Once an object is declared, nothing you do will change it's type. Objects don't change types once created.

Since myfunction() returns a reference, b 's assignment operator uses that as the right-hand-side. It doesn't make b a reference -- it just copies stuff from the thing returned by myfunction() , which just so happens to be a reference to something else.

is ba normal object?

Yes. Well, if I'm honest, I don't know what you mean exactly by "normal object." But in whatever sense you mean it, the answer is sureley yes. It's not a reference, and there's nothing magic about b (or anything else in C++, though it may seem so.)

Object b has already been constructed in the line above, so it will not call copy constructor but the assignment operator.

// Using copy constructor:
Test a;
Test b = a.myfunction();

// Using assignment operator
Test c;
c = a.myfunction();

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