c++referencetemporaryobject-lifetimeanonymous-objects

Is there a way to be sure that a const reference stored in class will always refer to a valid object?


I have written the following sample code:

#include <iostream>

class B
{
  int Value;

  public:
  B(int V) : Value(V) {}

  int GetValue(void) const { return Value;}
};

class A
{
  const B& b;

  public:
  A(const B &ObjectB) : b(ObjectB) {}

  int GetValue(void) { return b.GetValue();}

};


B b(5);

A a1(B(5));

A a2(b);

A a3(B(3));


int main(void)
{
  std::cout << a1.GetValue() << std::endl;
  std::cout << a2.GetValue() << std::endl;
  std::cout << a3.GetValue() << std::endl;

  return 0;
}

Compiled with mingw-g++ and executed on Windows 7, I get

6829289
5
1875385008

So, what I get from the output is that the two anonymous object are destroyed as the initialization has completed, even if they are declared in a global context.

From this my question: does is exist a way to be sure that a const reference stored in class will always refer to a valid object?


Solution

  • No, there is not. Remember that references are pointers under the hood, and normally don't control the lifetime of the object they reference (see here for an exception, although it doesn't apply in this case). I would recommend just having a B object, if this is in a piece of code that you need.

    Also, you could utilize an object such as a shared_ptr in C++11, which will only eliminate the object once both the pointer in the function and in the object have been destroyed.