Why does this code work correctly?
struct A {
std::string value = "test"s;
A() { std::cout << "created" << std::endl; }
~A() { std::cout << "destroyed" << std::endl; }
};
int main() {
A* ptr = nullptr;
{
A a;
ptr = &a;
}
std::cout << ptr->value << endl; // "test"
}
output:
- created
- destroyed
- test
Or this example:
struct A {
const std::string* str = nullptr;
A(const std::string& s) : str(&s) {}
};
int main()
{
A a = std::string("hello world");
std::cout << *a.str;
return 0;
}
output:
- hello world
In the first case, it seemed to me that when object A was destroyed, the content would become invalid, but I was able to retrieve the string.
In the second case, I took rvalue by constant reference, but extending the life of the object should work as long as the reference is valid. I thought that after the constructor worked, the string should have been destroyed. Why is this not happening?