dimanche 21 octobre 2018

Calling `delete` on an object owned by a `unique_ptr` using another pointer

I have a pointer to class initialized by the new operator. Then I use this pointer to setup a std::unique_ptr. Now, as far as my understanding goes, the following code has double delete, once the manually called delete operator and then when the unique pointer goes out of scope. How does this code run "correctly", i.e., without a runtime exception?

#include <iostream>
#include <memory>

class A
{
public:
    A()
    {
        std::cout<<"In A::A()\n";
    }
    ~A()
    {
        std::cout<<"In A::~A()\n";
    }
    void printMyStr()
    {
        std::cout<<"In A::printMyStr()\n";
    }
};

int main()
{
    std::cout<<"hello world!\n";
    A * pa = new A();
    std::unique_ptr<A> upa(pa);
    pa->printMyStr();
    upa->printMyStr();
    delete pa;  // How does this not create problems?
    return 0;
}

Output:

hello world!
In A::A()
In A::printMyStr()
In A::printMyStr()
In A::~A()
In A::~A()

Clearly the destructor runs twice, even if there is only one object that is created. How is this possible?

Note: I am using gcc 7.3.0 on 64-bit linux.

Aucun commentaire:

Enregistrer un commentaire