Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanded life-span of variables through std::unique_ptr

Tags:

c++

unique-ptr

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?

like image 378
nwn Avatar asked Feb 15 '23 14:02

nwn


1 Answers

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.

like image 195
Benjamin Lindley Avatar answered Mar 02 '23 15:03

Benjamin Lindley