Increased service life of variables via std :: unique_ptr

With C ++ 11 unique_ptr , the lifetime of an object seems to be extended beyond its usual scope, as in the following (rather far-fetched) 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 c character, which will usually be released at the end of the scope, remains until the end of the program. The second output is "Y", showing that unique_ptr not just copying its value.

Is it recommended to extend the life of a variable?
Is it safe or bear the same dangers as the link?

+4
source share
1 answer

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.

+8
source

Source: https://habr.com/ru/post/1496934/


All Articles