Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an obejct which is created inside a function

Tags:

c++

visual-c++

when I create an object inside a function it should be automatically deleted when the function exists. e.g. the object F should be automatically deleted when getFoo() exits. However still we are able to access F when we call getFoo. How?

     Foo getFoo()
     {    Foo F;
          return F;
     }
like image 201
user570593 Avatar asked Dec 22 '25 16:12

user570593


2 Answers

You are not accessing the object which was created inside the function. A copy is made on the stack before returning from the function. And of course the object which was created inside the function scope was destroyed when the function returned. By destruction, I mean the location on the stack on which it existed is no more valid.

like image 153
nishantsingh Avatar answered Dec 24 '25 05:12

nishantsingh


The object is copied to the caller.

Theoretically the following code

Foo a = getFoo();
  • calls the function
  • F is constructed
  • a is copy-constructed from F
  • F is destroyed

even funnier is this

Foo b;
b = getFoo();
  • b is constructed
  • calls the function
  • F is constructed
  • unnamed temporary object (temp) is copy-constructed from F
  • F is destroyed
  • assignment operator is called from temp to b
  • temp is destroyed.

Thankfully modern compiler support return value optimization to prevent this. This also is also one of the very few exceptions to the "as if" mantra regarding code-optimizations.

You may test this with your favorite debuger with this example code (tip: note the addresses of the objects):

struct A {
  A() {
    i = 0; 
  }
  A(const A& o) {
    i = o.i;
  }

  A& operator=(A& o) {
    i = o.i;
    return *this;
  }

  ~A() {
    i = 0;
  }
  int i;
};

A getA() {
  A a;
  return a;
}

int main(){
  A a = getA();
  A b;
  b = getA();

  return 0;
}
like image 31
vlad_tepesch Avatar answered Dec 24 '25 05:12

vlad_tepesch