15

I'm studying the C++ Primer 4th edition by Stanley B. Lippman. In section 12.4.1, when the author talks about constructor initializers, he gives this example:

class ConstRef {
  public:
    ConstRef(int ii);
  private:
    int i;
    const int ci;
    int &ri;
};
// OK: explicitly initialize reference and const members.
ConstRef::ConstRef(int ii): i(ii), ci(i), ri(ii) { }

I suspect that this may cause a dangling reference ri pointing to ii, which is a temporary. Am I right?

Palec
  • 12,743
  • 8
  • 69
  • 138
chanp
  • 675
  • 7
  • 16
  • 16
    clang++ is real helpful: `warning: binding reference member 'ri' to stack allocated parameter 'ii' [-Wdangling-field]` – Mat May 25 '12 at 10:49
  • Having googled around to see what it's like, the error report looks really great. – chanp May 25 '12 at 11:04

1 Answers1

13

I think so too. Try this

ConstRef::ConstRef(int ii): i(ii), ci(i), ri(i) { }
Jeremy Wall
  • 23,907
  • 5
  • 55
  • 73
triclosan
  • 5,578
  • 6
  • 26
  • 50