vendredi 21 juin 2019

How does std::unique_ptr work when it goes out of scope after the object it owns has been manually deleted?

I may not have worded the title correctly, but it is easier to explain in the following example, and then perhaps someone can edit the title.

Consider the following snippet of code:

#include <iostream>
#include <memory> // for std::unique_ptr

class Resource
{
public:
    Resource() { std::cout << "Resource acquired\n"; }
    ~Resource() { std::cout << "Resource destroyed\n"; }
};

int main()
{
    Resource* res = new Resource;
    std::unique_ptr<Resource> res1(res); // Resource created here
    delete res;

    std::cout << "res1 is " << (static_cast<bool>(res1) ? "not null\n" : "null\n");

    return 0;
}

This prints:

$ ./a.out 
Resource acquired
Resource destroyed
res1 is not null
Resource destroyed

We created a dynamically allocated resource, and then created a unique pointer (res1) who owns this resource. The unique pointer allows us to not worry about having to manually delete the resource.

But let's suppose we manually delete the resource anyway (without setting it to null after) as in the above code. Then when res1 goes out of scope, wouldn't it be trying to delete something that has already been deallocated?

Aucun commentaire:

Enregistrer un commentaire