I am wondering if he could accidentally use a pointer to a const link associated with the destroyed stack variable.
I read that the lifetime of the const constant extends to rvalues, so this is a "normal" reference to the constant, but at the end of the ctor of the storage ref should be destroyed, isn't It?
Is the link lifetime constant maintained because I got its address in a pointer or is it just luck?
Real time example
#include <iostream> class Storage { public: Storage(const int& ref) { p = &ref; } const int* Get() const { return p; } private: const int* p; }; int main() { Storage* s = nullptr; { int someValue = 42; std::cout << &someValue << std::endl; s = new Storage(someValue); } const int* p = s->Get(); std::cout << p << std::endl; std::cout << *p << std::endl; }
It also works with the Live example string .
#include <iostream> struct Dummy { int value; }; class Storage { public: Storage(const Dummy& ref) { p = &ref; // Get address of const reference } const Dummy* Get() const { return p; } private: const Dummy* p; }; int main() { Storage* s = nullptr; { Dummy dummy; dummy.value = 42; std::cout << &dummy << std::endl; s = new Storage(dummy); } const Dummy* p = s->Get(); std::cout << p << std::endl; std::cout << p->value << std::endl; }
source share