Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

One thing you can do in class A:

A(B&&) = delete;

That way, the two lines that try to construct an A from a B temporary will fail to compile.

That obviously won't prevent you providing some other B object with a lifetime shorter than the A object referencing it, but it's a step in the right direction and may catch some accidental/careless abuses. (Other answers already discuss design scenarios and alternatives - I won't cover that same ground / whether references can be safe(r) in the illustrated scenario is already an important question.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top