gpt4 book ai didi

c++11 - 用于weak_ptr 的static_pointer_cast

转载 作者:行者123 更新时间:2023-12-03 22:30:45 25 4
gpt4 key购买 nike

在 c++0x 中,std::shared_ptr 有一个 std::static_pointer_cast,但 std::weak_ptr 没有等效的方法。这是有意为之,还是疏忽大意?如果是疏忽,我将如何定义适当的功能?

最佳答案

这应该为你做:

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()反而。

关于c++11 - 用于weak_ptr 的static_pointer_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6065954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com