【发布时间】:2011-08-29 06:52:53
【问题描述】:
在 c++0x 中,std::shared_ptr 有一个 std::static_pointer_cast,但 std::weak_ptr 没有等效方法。这是故意的,还是疏忽?如果有疏忽,我将如何定义合适的功能?
【问题讨论】:
在 c++0x 中,std::shared_ptr 有一个 std::static_pointer_cast,但 std::weak_ptr 没有等效方法。这是故意的,还是疏忽?如果有疏忽,我将如何定义合适的功能?
【问题讨论】:
省略是故意的,因为尽管它的名字,std::weak_ptr 不是指针类型并且不提供指针接口(operator ->、operator *、static_pointer_cast 等)。
【讨论】:
霍华德的版本是正确的,但在许多情况下,将 weakptr.lock() 作为参数简单地传递给 std::static_pointer_cast 是有意义的:
std::weak_ptr<A> a = ...;
std::weak_ptr<B> b = std::static_pointer_cast<B>(a.lock());
此语法明确显示正在发生的事情,并使代码易于阅读。
【讨论】:
这应该为你做:
template<class T, class U>
std::weak_ptr<T>
static_pointer_cast(std::weak_ptr<U> const& r)
{
return std::static_pointer_cast<T>(std::shared_ptr<U>(r));
}
如果weak_ptr 已过期,这将引发异常。如果您希望得到一个空的weak_ptr,请改用r.lock()。
【讨论】:
static_pointer_cast 是一个通用名称,可用于指针类型为通用的代码。