是的,S对象在被调用时仍然存在foo(),因此您的s引用仍然有效。
的别名构造函数将p增加当前持有的S对象的引用计数,使该对象保持活动状态,同时保留您为其构造函数提供的对象。完成使用后,它将减少引用计数。pspnullptrp
您可以通过查询 refcount 来验证这一点:
std::shared_ptr<S> ps = std::make_shared<S>();
auto& s = *ps; // Keep a reference to the S.
auto p = std::shared_ptr<S>(ps, nullptr); // Aliasing c'tor with null pointer.
ps = nullptr;
assert(ps == nullptr);
assert(p == nullptr);
cout << ps.use_count() << endl; // prints 0
cout << p.use_count() << endl; // prints 1
foo(s); //< S is still alive here
演示
如果您删除该ps = nullptr;语句,您将看到两者ps并p报告 refcount 为 2:
std::shared_ptr<S> ps = std::make_shared<S>();
auto& s = *ps; // Keep a reference to the S.
auto p = std::shared_ptr<S>(ps, nullptr); // Aliasing c'tor with null pointer.
//ps = nullptr;
assert(ps != nullptr);
assert(p == nullptr);
cout << ps.use_count() << endl; // prints 2
cout << p.use_count() << endl; // prints 2
foo(s); //< S is still alive here
演示