-2

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;
}
gudge
  • 1,053
  • 4
  • 18
  • 33
  • I do not understand the negative votes around the question. Smart pointers in C++ are not easy concepts to grasp and get your head around for commoners. It is not like program not compiling, keyword missing etc. The question is small with a working piece of code. What else is expected for people asking questions ? – gudge Jun 26 '15 at 10:45

1 Answers1

1

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
sehe
  • 374,641
  • 47
  • 450
  • 633
  • With the statement above there will be a leak right for q if I do not explicitly free it ? – gudge Jun 25 '15 at 11:17
  • No. The shared pointers will both adequately free their owned resources on destruction/re-assignment – sehe Jun 25 '15 at 11:34
  • I ran the code under valgrind. It said invalid read of size 4 at : std::cout << *p << std::endl; and said definetly leaked 4 bytes – gudge Jun 25 '15 at 11:51
  • @gudge Oh, aha, I've misread the `std::cout` lines (why would you be doing that, by the way? You explicitly re-assign `ps`, so obviously `p` is dangling. I supposed you did `std::cout << *ps` and `std::cout << *qs` there. And since you never free `q` that's definitely leaked. – sehe Jun 25 '15 at 12:09
  • Please tell us _what you're trying to achieve_ (not /how/). So we can give a useful answer – sehe Jun 25 '15 at 12:10
  • Sorry for the confusion. I want to use ps for operations on p and then use it for operations on q. I do not wish to re declare another shared_ptr for q. I should be able to use p even after ps is not pointing to p. – gudge Jun 25 '15 at 12:12
  • That's not what shared_ptr is for. End of story. Rethink the logic. – sehe Jun 25 '15 at 12:51