With the C++11 unique_ptr
, an object's lifespan seems to be extended outside of its usual scope like in the following (rather contrived) example:
#include <iostream>
#include <memory>
using namespace std;
int main()
{
unique_ptr<char> uPtr(nullptr);
{
char c = 'X';
cout << "c = " << c << endl;
uPtr.reset(&c);
c = 'Y';
}
cout << "c = " << *uPtr << endl;
return 0;
}
Output:c = X
c = Y
The character c, which would usually be released at the end of the scope, survives until the end of the program. The second output is 'Y', showing that the unique_ptr
does not simply copy its value.
Is it recommended to extend the lifespan of a variable in an way?
Is this safe, or does it carry the same dangers as a reference?
With the C++11 unique_ptr, an object's lifespan can be extended outside of its usual scope
No, it can't.
The character c, which would usually be released at the end of the scope, survives until the end of the program.
No it doesn't, it survives until the end of the scope, just as normal.
The second output is 'Y', showing that the unique_ptr does not simply copy its value.
You're right, unique_ptr
does not copy the value it points to. But your output here is irrelevant, because your code has undefined behavior when you dereference that pointer, because the thing it points to no longer exists. The code has undefined behavior again when the unique_ptr
is destroyed, and calls delete
on that location (although you can provide a no-op deleter).
Is it recommended to extend the lifespan of a variable in an way? Is it safe...
Clearly no and no.
or does it carry the same dangers as a reference?
Yes, this is similar to returning a reference to a local variable from a function. It's even more similar to having a dangling pointer and dereferencing it, with the addition that delete
is called on the location for an extra dose of undefined behavior.
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