[英]Casting shared_ptr<T> to shared_ptr<void>
I have a structure: 我有一个结构:
struct Params {
std::shared_ptr<void> user_data;
/* ... */
};
I want to use it like this: 我想这样使用它:
int main() {
std::shared_ptr<SpecializedParams> sp(new SpecializedParams(100));
Params params;
/* ... */
params.user_data = std::static_pointer_cast<void>(sp);
/* ... */
std::shared_ptr<SpecializedParams> sp2 =
std::static_pointer_cast<SpecializedParams>(
params.user_data
);
/* ... */
return 0;
}
Is this valid and safe? 这有效且安全吗?
The code, that actual deletes the shared object is determined when the shared pointer is created (that's why you need a complete type, when constructing the shared_ptr and not, when destructing the shared_ptr). 实际删除共享对象的代码是在创建共享指针时确定的(这就是为什么在构造shared_ptr时需要完整类型,而不是在破坏shared_ptr时)。 Thus even when your shared_ptr is the last pointer that points to your SpecializedParams object, the object will get correctly destroyed.
因此,即使您的shared_ptr是指向SpecializedParams对象的最后一个指针,该对象也会被正确销毁。
This should be safe as the void casted item is a shared_ptr too. 这应该是安全的,因为void casted item也是shared_ptr。 It will add a reference to the existing element and it will not be released until the void casted item goes away.
它将添加对现有元素的引用,并且在void casted item消失之前不会释放它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.