Const link lifetime associated with stack variable destroyed

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; } 
+4
source share
2 answers

There really is a someValue pointer in the s variable, as someValue fell out of scope. Therefore, your code demonstrates undefined behavior.

Your comment about "constant constant reference resource" extends to rvalues ​​"is true in some cases, but someValue is an lvalue.

+9
source

The compiler probably assigns stack space to all local variables at the beginning, so someValue is still in the same place in memory even after it goes out of scope. Of course, another compiler can do something different, and it can be overwritten by the next local variable.

For your second example, if you wrote ~ Dummy () {value = 0; }, then this will not work, proving that the lifetime of the stub object has not been extended.

0
source

All Articles