【发布时间】:2019-07-28 10:31:46
【问题描述】:
通常,如果您使用std::shared_ptr 指向一个对象,并且您想创建另一个指向该对象但不共享所有权的指针,您将创建一个std::weak_ptr。
// Create a shared pointer to own the object
std::shared_ptr<int> p = std::make_shared<int>(42);
// Create a weak pointer (that does not own the object)
std::weak_ptr<int> q(p);
// Use the weak pointer some time later
if (std::shared_ptr ptr = q.lock()) {
// use *ptr
}
我的问题是,当涉及到std::unique_ptr 时,你是如何做到这一点的?
使用唯一指针可确保当前资源由std::unique_ptr 本身独占。但是,如果我想创建一个指向不拥有该资源的同一资源的指针怎么办?我不能使用std::weak_ptr,因为弱指针旨在处理来自std::shared_ptr 的引用计数。我会在这里使用原始指针吗?还是有更好的选择?
// Create a unique pointer to own the object
std::unique_ptr<int> p = std::make_unique<int>(42);
// Create a non-owning pointer to the same object
// Is this really the best way?
int* q = p.get();
// Use the pointer some time later
if (q != nullptr) {
// Imagine this may be multithreaded...
// what happens if p.reset() is called by another thread while the current thread is RIGHT HERE.
// use *q
}
我能想到的创建指向std::unique_ptr 拥有的对象的非拥有指针的唯一方法是使用原始指针,但正如您从上面的代码中看到的那样,这可能会导致线程应用程序出现问题。有没有更好的方法来实现相同的目标?
【问题讨论】:
-
是的,只使用原始指针,或者,C++ 核心指南对非拥有指针有一些特殊类型,我想不起来了。
-
视情况而定。
weak_ptr提供了在对象锁定时延长对象生命周期的语义。您是否希望在unique_ptr的情况下使用它,或者您是否可以在使用对象时删除它? -
@SergeyA 是
gsl::observer<T>,iirc 是T*的别名 -
“使用原始指针可能会导致多线程问题”。使用几乎任何东西,包括智能指针,都可能导致多线程问题
-
我会为
std::unique_ptr和std::shared_ptr使用原始指针,除非应用程序需要std::weak_ptr。为不使用的东西付费是没有意义的。
标签: c++ c++11 shared-ptr unique-ptr weak-ptr