2

Why the code below outputs 1 1 rather than 2 1? It seems that smart pointer initialized with this in class does not increase use_count


#include <iostream>
#include <memory>

using namespace std;

struct T1 {
    using tp1 = shared_ptr<T1>;
    tp1 a;
    T1() : a(this) {}
};

int main() {
    auto x = make_shared<T1>();
    cout << x.use_count() << endl;
    x->a = nullptr;
    cout << x.use_count() << endl;
}
ZhiyuanLck
  • 191
  • 1
  • 1
  • 5
  • 1
    `x` and `a` don't know about each other. You can't initialize multiple `shared_ptr` from the same raw pointer. I'm sure there is a duplicate, I'll see if I can find it. – François Andrieux Feb 24 '20 at 15:56
  • 2
    An object should not have a `shared_ptr` member to `this`, even if you can get a legitimate `shared_ptr` to initialize that member with. By doing that, you ensure that the object can never be destroyed unless the member is explicitly and manually cleared. An object should not own itself. You are likely to leak it which defeats the purpose of using smart pointers in the first place. – François Andrieux Feb 24 '20 at 16:00

0 Answers0