Copy constructor called even when returning by reference?

Posted by Johnyy on Stack Overflow See other posts from Stack Overflow or by Johnyy
Published on 2010-12-24T06:48:25Z Indexed on 2010/12/24 6:54 UTC
Read the original article Hit count: 220

Filed under:

Hi,

I am testing the return of local objects by reference. My original test went well but something else happens unexpected.

#include <iostream>

using namespace std;

class MyInt {
public:
    MyInt(int i){
        value = new int(i);
    }
    ~MyInt(){
        delete value;
    }
    int getValue(){
        return *value;
    }
    MyInt(const MyInt &b){
        cout<<"Copy"<<endl;
    }
private:
    int* value;
};

MyInt& returnref(){
    MyInt a(10);
    cout<<"Returning from returnref()"<<endl;
    return a;
}

int main(){
    MyInt a = returnref();
    cout<<a.getValue()<<endl;
    return 0;
}

My console prints "Returning from ..." then "Copy" then a random value.

My understanding of pass by reference is that it does not need to make any copy. Why is it not doing what I expected?

© Stack Overflow or respective owner

Related posts about c++