简体   繁体   English

投射shared_ptr <Type> 到weak_ptr <void> 然后回来

[英]Casting shared_ptr<Type> to weak_ptr<void> and back

How would I get a weak_ptr<void> to a shared_ptr<Type> ? 我如何将weak_ptr<void>转换为shared_ptr<Type>

How would I lock a weak_ptr<void> and ultimately produce a shared_ptr<Type> ? 我如何锁定weak_ptr<void>并最终产生shared_ptr<Type>

Type has a non-trivial destructor, is it right to assume weak_ptr<...> will never call this destructor? Type有一个非平凡的析构函数,是否假定weak_ptr<...>永远不会调用此析构函数是正确的?

The void weak pointer is what I want in this case, it's used only to keep tabs on the reference count of shared pointers of multiple types, and give out shared pointers to existing objects without itself owning the object (it's part of a one object many references resource manager). 在这种情况下,我需要的是void弱指针,它仅用于保持对多种类型的共享指针的引用计数的控制,并给出对现有对象的共享指针,而无需自己拥有该对象(它是一个对象的一部分,很多参考资源管理器)。

How would I get a weak_ptr<void> to a shared_ptr<Type> ? 我如何将weak_ptr<void>转换为shared_ptr<Type>

std::shared_ptr<Type> is implicitly convertible to std::weak_ptr<void> . std::shared_ptr<Type>可隐式转换为std::weak_ptr<void>

How would I lock a weak_ptr<void> and ultimately produce a shared_ptr<Type> ? 我如何锁定weak_ptr<void>并最终产生shared_ptr<Type>

Call lock() to get std::shared_ptr<void> , then use std::static_pointer_cast . 调用lock()以获得std::shared_ptr<void> ,然后使用std::static_pointer_cast

Type has a non-trivial destructor, is it right to assume weak_ptr<...> will never call this destructor Type有一个非平凡的析构函数,是否假定weak_ptr<...>永远不会调用此析构函数是正确的

Yes. 是。 Whenever the last shared_ptr is destroyed, the object is destroyed. 每当最后一个shared_ptr被销毁时,该对象就会被销毁。 If you want to keep the object alive, you should be storing shared_ptr<void> and not weak_ptr<void> . 如果要使对象保持活动状态,则应存储shared_ptr<void>而不是weak_ptr<void> If you don't want to keep the object alive but you just want the weak_ptr to always know the reference count, then there is no problem. 如果您不想让对象保持活动状态,而只想使weak_ptr始终知道引用计数,那么就没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM