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?
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.
I think so too. Try this
ConstRef::ConstRef(int ii): i(ii), ci(i), ri(i) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With