samedi 1 février 2020

unique_ptr ownership craziness

Have a look at the sample code below and it's output.

I have a simple Base class with just an int* member variable.

I create a unique_ptr from an existing object of Base.

When the pointer and the object goes out of scope, the destructor is called twice, first for the unique_ptr and then for the object.

I thought the unique_ptr would own the object and take care of destroying it??

#include <iostream>
#include <string>
#include <vector>
#include <memory>

class Base
{
protected:
    int* status;

public:
    // default constuctor
    Base() : Base(0)
    {
    }

    // custom constuctor
    Base(int a){
        this->status = new int(a);
        std::cout << "\n" << "Base:" << *status;
    }

    // destructor
    ~Base(){
        std::cout << "\n" << "Base Destroyed:" << *status;
        delete this->status;
    }

    void info(){
        std::cout << "\n" << "Base status:" << *status;
    }    
};

int main(int argc, const char * argv[])
{
    {
        Base base(1);

        // create from existing object
        std::unique_ptr<Base> uptrBase1 = std::make_unique<Base>(base);

        // create from new
        std::unique_ptr<Base> uptrBase3 = std::make_unique<Base>();

        std::cout<<"\n" << "Ending scope";
    }

    std::cout<<"\n";
    return 0;
}

The output I get is as below:

Base:1
Base:0
Ending scope
Base Destroyed:0
Base Destroyed:1
Base Destroyed:0TestCppProject(4373,0x1000d5dc0) malloc: *** error for object 0x1005ac970: pointer being freed was not allocated
TestCppProject(4373,0x1000d5dc0) malloc: *** set a breakpoint in malloc_error_break to debug
Program ended with exit code: 9

Aucun commentaire:

Enregistrer un commentaire