Giving up ownership of a memory without releasing it by shared_ptr

235 views Asked by At

Is there a way I can make the shared pointer point to a different memory location without releasing the memory.pointed by it currently

Please consider the code:

#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <iostream>

int
main()
{
    int *p = new int();
    *p = 10;
    int *q = new int();
    *q = 20;

    boost::shared_ptr<int> ps(p);

    // This leads to a compiler error
    ps = boost::make_shared<int>(q);

    std::cout << *p << std::endl;
    std::cout << *q << std::endl;
    return 0;
}
1

There are 1 answers

7
sehe On

You can't.

Of course you can release and reattach, while changing the deleter to a no-op

To be honest, it looks like you'd just want

ps = boost::make_shared<int>(*q);

Prints (live on Coliru):

0
20