Search code examples
c++referencedangling-pointer

Is this constructor initializer causing a dangling reference?


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?


Solution

  • I think so too. Try this

    ConstRef::ConstRef(int ii): i(ii), ci(i), ri(i) { }