1

Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
return reference to local variable

This is a sample program written for checking the scope of a local class object inside a function. Here I am creating an object of class A and assigning values to it and returns that object by reference in Function(). I want to know that when the scope of the variable will end?.Since it is a stack object(not pointer), Is it will be destructed in the end of the Function()? If so what will happen when its reference value is assigned to a new object?

  #include "stdafx.h"
  #include <iostream>

  class A
  {
  public:
    int a, b;
    A(int aa, int bb)
    {
      a = aa;
      b = bb;
    }
    A(){}
  };

  A& Function()
  {
    A object;
    object.a = 10;
    object.b = 20;
    return object;
  }

  int _tmain(int argc, _TCHAR* argv[])
  {
    A aaa = Function();
    std::cout<<"\nValue : "<<aaa.a<<" "<<aaa.b;
    getchar();
    return 0;
  }
Community
  • 1
  • 1
Ajesh PN
  • 45
  • 1
  • 6

4 Answers4

2

Since it is a stack object(not pointer), Is it will be destructed in the end of the Function()?

Yes.

If so what will happen when its reference value is assigned to a new object?

Undefined behaviour.

If you are creating something for the purpose of returning it, return it by value. That's what values are for.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    The same behavior will occur if i changed the stack object to a pointer. right?? – Ajesh PN Jun 07 '12 at 11:16
  • @AjeshPN: If you return a dynamically allocated pointer from the function *by value* then the pointer which accepts the returned pointer will point to the dynamic memory and it will work fine. – Alok Save Jun 07 '12 at 11:22
  • 1
    @AjeshPN: Returning a pointer to a stack allocated object is Undefined Behavior(*Technically,dereferencing such a pointer is where Undefined Behavior happens*) – Alok Save Jun 07 '12 at 11:26
2

What happens?

Undefined behavior is what happens!

A stack allocated object is local/automatic because all allocations of these objects are implicitly cleaned once the scope({, }) in which they reside ends.

Returning reference to an local object is an undefined behavior.
Undefined behavior means literally any behavior can be seen. The program might work or it might crash or behave randomly. Just it is not a valid c++ program and anything can happen.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

The object will be destructed at the end of the Function(). Return the data by pass by value mechanism.

Aneesh Narayanan
  • 3,220
  • 11
  • 31
  • 48
0

I believe your question is answered here: In C++, is it safe to extend scope via a reference? However, it's somewhat old. You may want to look into C++11, rvalue references and move semantics.

Community
  • 1
  • 1
Matthew Alpert
  • 5,993
  • 1
  • 16
  • 13