0

Is the following code safe?

class B {
  public:
    int& b;
    B (int& _b) :
      b(_b) {}
};

B* foo() {
  int a;
  return new B(a);
}

Will the reference in the object returned by foo point to nothing (since int a is going out of scope) or does the compile figure this out?

owagh
  • 3,428
  • 2
  • 31
  • 53
  • 6
    `B::b` will be a dangling reference as local variable `a` no longer exists when `foo()` returns, as you already state. – hmjd Jun 15 '12 at 20:57
  • See 17.6.4.3.2/2: *Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.*. Use `b_` instead. – dirkgently Jun 15 '12 at 21:05
  • 1
    @dirkgently, that name isn't in the global namespace, the name is ok – Jonathan Wakely Jun 15 '12 at 21:16
  • @dirkgently: http://stackoverflow.com/a/228797/14065 – Martin York Jun 15 '12 at 21:16
  • @owagh: In the standard: http://stackoverflow.com/a/4653479/14065 Though most people will usually tell you what version as section numbers may change slightly between version, though section names will remain the same. – Martin York Jun 15 '12 at 21:18

1 Answers1

5

The compiler might warn you, but the newly created object definitely contains a dangling, invalid reference, as the object a stops existing at the end of the scope of foo.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084