Tuesday, 13 August 2013

Expanded life-span of variables through std::unique_ptr

Expanded life-span of variables through std::unique_ptr

With the C++11 unique_ptr, an object's lifespan can 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;
}
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?

No comments:

Post a Comment