Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ return local object

Tags:

Several co-workers and I are having a debate about what happens when a local variable (allocated on the stack) is returned from a C++ method.

The following code works in a unit test, but I believe that is only because the unit test is lucky and doesn't attempt to reuse the memory on the stack used by obj.

Does this work?

static MyObject createMyObject() {     MyObject obj;     return obj; } 
like image 650
Brian Avatar asked Jun 14 '11 22:06

Brian


People also ask

Can we return local variable in C?

Yes you are returning an array, which is actually a pointer behind the scenes, to the address of the memory location where the contents of the variable you've initialised is stored.

Can you return a local object in C++?

If a method or function returns a local object, it should return an object, not a reference. If a method or function returns an object of a class for which there is no public copy constructor, such as ostream class, it must return a reference to an object.

What does returning an object do?

It would mean make a copy and return it. The difference is that if you return pointer to objects internal variable that object state could be modified from outside. If you return copy that copy can be modified and the original object will not change.

How do you return an object from a value in C++?

Returning Object as argumentobject = return object_name; Example: In the above example we can see that the add function does not return any value since its return-type is void. In the following program the add function returns an object of type 'Example'(i.e., class name) whose value is stored in E3.


1 Answers

What happens is that the copy constructor gets called to make a copy of the local object, and that is what the caller receives.

The compiler may eliminate the copy in a process called copy elision, but that's at the discretion of the compiler - you don't have much control over it.

This pattern is capable of producing the problems you're afraid of, but only if you're returning a pointer or reference to the local object.

like image 56
Mark Ransom Avatar answered Sep 19 '22 13:09

Mark Ransom