Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 654
chanp Avatar asked May 25 '12 10:05

chanp


People also ask

What is dangling reference in C++?

C++ Undefined Behavior Accessing a dangling referenceIt is illegal to access a reference to an object that has gone out of scope or been otherwise destroyed. Such a reference is said to be dangling since it no longer refers to a valid object.


1 Answers

I think so too. Try this

ConstRef::ConstRef(int ii): i(ii), ci(i), ri(i) { }
like image 88
triclosan Avatar answered Oct 20 '22 01:10

triclosan