0

Is it safe to remove the only shared_ptr reference to itself inside a method? Something like the following. If two objects, one of class A and the other of class B, points to each other via their pB_ and pA_. Suppose pB_ is the only reference to the object of class B. Then I call A::method() on the object of class A. Will there be any problem?

#include <iostream>
using std::shared_ptr

class B;
class A {
 public:
  void method() {
    pB_->method();
  }
  shared_ptr<B> pB_;
};

class B {
 public:
  void method() {
    pA_->pB_.reset();

    // Is this OK? And is it safe if I don't do this? 
    some_other_data_ = 10;
  }
  shared_ptr<A> pA_;

  int some_other_data_;
};
shaoyl85
  • 1,854
  • 18
  • 30
  • This is eerily similar to what used to be a ridiculously common mistake made by COM programmers many moons ago. `if (--m_dwRefCount == 0) delete this; return m_dwRefCount;` I cannot tell you how many times I saw that code crash and burn in *professionally* published components. – WhozCraig Feb 19 '15 at 06:21
  • That is possibly worse as it's also thread-unsafe. Two threads may decide at the same moment to stop using your COM component so you'd need that interlocked decrement function. – MSalters Feb 19 '15 at 14:01

1 Answers1

1

Resetting that pointer will result in the B object being deleted, so no, it is not okay to access one of its members after that point. For more info, see: Is it safe to `delete this`?

Community
  • 1
  • 1
Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • Thank you! How about if I don't access the data after reset. Is that case OK? – shaoyl85 Feb 19 '15 at 06:26
  • The rules are same as they would be if you called `delete` on an object allocated by `new`. If you want to find out more, punch "c++ delete this" into your favorite search engine. (Or look [here](http://stackoverflow.com/questions/3150942/c-delete-this).) – David Schwartz Feb 19 '15 at 07:18