With C ++ 11 unique_ptr, you can extend the validity of an object beyond its normal scope
No he can not.
The c character, which will usually be released at the end of the scale, remains until the end of the program.
No, this is not so; it survives to the end of the region, as usual.
The second output is "Y", indicating that unique_ptr does not just copy its value.
You are right, unique_ptr does not copy the value it points to. But your conclusion here does not matter, because your code has undefined behavior when you play this pointer, because the thing pointed to no longer exists. The code has undefined behavior again when unique_ptr destroyed, and calls delete at this point (although you can provide a non-op deleter).
Is it recommended to extend the life of a variable? It's safe...
Clearly, no and no.
or does it carry the same dangers as the link?
Yes, it is like returning a link to a local variable from a function. This is even more like having a dangling pointer and dereferencing it, adding that delete is called at the location for an extra dose of undefined behavior.
source share