1

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.

2 Answers 2

5

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.

5
  • thanks, initializing "a" and then assign it to the return value works.
    – Johnyy
    Dec 24, 2010 at 6:54
  • I intentionally wanted to see the undefined behavior.
    – Johnyy
    Dec 24, 2010 at 6:56
  • 4
    @Johnyy "I intentionally wanted to see the undefined behavior"... you do realize that "undefined behavior" means it can do pretty much anything, right? There is no specific undefined behavior to check for. Dec 24, 2010 at 7:14
  • @Johnyy: Laurence is right. The scary thing is, is that code like this will probably work correctly until you make another function call which will overwrite the stack memory that used to hold a
    – Zan Lynx
    Nov 2, 2011 at 15:15
  • @ZanLynx ...code like that will work fine until it's running in front of a customer... ;-) Aug 29, 2014 at 13:52
4

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!

1
  • 2
    This is still dangerous. After returning from the function a would be destroyed so this is still UB. Dec 24, 2010 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.