Pages

Monday, 29 August 2016

Taking ownership of the memory from std::shared_ptr

There is no function in shared_ptr using that you take owner ship of the under lying pointer.

This may be because there might be multiple object which is referring to the same pointer.

shared_ptr has a constructor which takes an additional parameter which is used to delete the allocated object.

We will use this deleter to control the ownership.

A simple deleter implementation is shown below,
class Deleter {
private:
    std::shared_ptr<bool> mOwn = std::make_shared<bool>(true);

public:
    void setOwn(bool v) {
        *mOwn = v;
    }

    void operator()(Test *p) {
        if (*mOwn) {
            delete p;
        }
    }
};

Now we can use the above Deleter class to control the ownership of the pointer. An example use is shown below.
Deleter dltr;
std::shared_ptr<Test> obj1 = std::shared_ptr<Test>(new Test(), dltr);
dltr.setOwn(false);

std::shared_ptr<Test> obj2 = obj1;

delete obj2.get(); // safe to delete


We can specify the deleter when we reset the pointer as well.
Test *tobj1 = new Test();
Test *tobj2 = new Test();

Deleter dltr;
dltr.setOwn(false);
std::shared_ptr<Test> obj1 = std::shared_ptr<Test>(tobj1, dltr);
obj1.reset<Test, Deleter>(tobj2, dltr);

delete tobj1; // safe to delete
delete tobj2; // safe to delete

No comments:

Post a Comment