使指向特定托管对象的所有共享指针无效
Invalidate all shared ptrs toward a specific managed object
在 C++11 中,是否可以让一个对象由多个 std::shared_ptr
管理。我想通过一个 std::shared_ptr
删除对象并使其他 shared_ptr
无效(设置为空或 null),这可能吗?如果不是,通知所有其他 "references"(自由使用该词)该对象不再有效的最佳方法是什么?
为此,必须将其他 shared_ptr
替换为 weak_ptr
。执行删除的 shared_ptr
是在这种情况下实际管理对象生命周期的那个。此时值得弄清楚您是否真的 需要共享所有权语义。一般来说,如果您发现自己尝试做一些界面不允许您做的事情,这表明您需要具有不同语义的东西。
或者,如果你真的不能从一个地方管理对象的生命周期,你可以使用 shared_ptr<unique_ptr<T>>
,但是这更麻烦(更不用说更慢了)并且最好避免。在这里,您将通过 reset
调整内部 unique_ptr
.
来删除对象
Here 是 weak_ptr
的一个很好的例子,当所有其他 "references" 不再有效时会收到通知。
#include <iostream>
#include <memory>
std::weak_ptr<int> gw;
void f()
{
std::cout << "use_count == " << gw.use_count() << ": ";
if (auto spt = gw.lock())
{ // Has to be copied into a shared_ptr before usage
std::cout << *spt << "\n";
}
else
{
std::cout << "gw is expired\n";
}
}
int main()
{
{
std::shared_ptr<int> sp = std::make_shared<int>(42);
gw = sp;
f();
}
f();
}
Output:
use_count == 1: 42
use_count == 0: gw is expired
在 C++11 中,是否可以让一个对象由多个 std::shared_ptr
管理。我想通过一个 std::shared_ptr
删除对象并使其他 shared_ptr
无效(设置为空或 null),这可能吗?如果不是,通知所有其他 "references"(自由使用该词)该对象不再有效的最佳方法是什么?
为此,必须将其他 shared_ptr
替换为 weak_ptr
。执行删除的 shared_ptr
是在这种情况下实际管理对象生命周期的那个。此时值得弄清楚您是否真的 需要共享所有权语义。一般来说,如果您发现自己尝试做一些界面不允许您做的事情,这表明您需要具有不同语义的东西。
或者,如果你真的不能从一个地方管理对象的生命周期,你可以使用 shared_ptr<unique_ptr<T>>
,但是这更麻烦(更不用说更慢了)并且最好避免。在这里,您将通过 reset
调整内部 unique_ptr
.
Here 是 weak_ptr
的一个很好的例子,当所有其他 "references" 不再有效时会收到通知。
#include <iostream>
#include <memory>
std::weak_ptr<int> gw;
void f()
{
std::cout << "use_count == " << gw.use_count() << ": ";
if (auto spt = gw.lock())
{ // Has to be copied into a shared_ptr before usage
std::cout << *spt << "\n";
}
else
{
std::cout << "gw is expired\n";
}
}
int main()
{
{
std::shared_ptr<int> sp = std::make_shared<int>(42);
gw = sp;
f();
}
f();
}
Output:
use_count == 1: 42
use_count == 0: gw is expired