Johnyy
Johnyy

Reputation: 2116

Copy constructor called even when returning by reference?

I am testing the return of local objects by reference (hopefully it is undefined behavior, to conform with my reading in Effective C++ ). 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?

EDIT: Don't return a reference to a local object, because it will be already destroyed outside of the function. I was just testing to see it actually happens that way.

Upvotes: 1

Views: 1717

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361322

Write this to avoid calling copy constructor:

 MyInt & a = returnref(); 
 //   ^^^  please note this '&' 

But returning reference of local object is not a good idea. Read Prasoon's comment below too!

Upvotes: 4

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99565

MyInt a in MyInt a = returnref(); is not a reference, so it should be initialized. That's why copy constructor was called. And you shouldn't return a reference to a temporary object (MyInt a(10) is allocated on the stack and will be destroyed on exit from function), it will lead to undefined behavior.

Upvotes: 5

Related Questions