How to return a class object by reference in C++?

后端 未结 5 1481
北恋
北恋 2020-12-07 20:53

I have a class called Object which stores some data.

I would like to return it by reference using a function like this:

    Object& return_Object         


        
5条回答
  •  无人及你
    2020-12-07 21:54

    You're probably returning an object that's on the stack. That is, return_Object() probably looks like this:

    Object& return_Object()
    {
        Object object_to_return;
        // ... do stuff ...
    
        return object_to_return;
    }
    

    If this is what you're doing, you're out of luck - object_to_return has gone out of scope and been destructed at the end of return_Object, so myObject refers to a non-existent object. You either need to return by value, or return an Object declared in a wider scope or newed onto the heap.

提交回复
热议问题