[英]Is there a way to cast a shared ptr to void pointer and then cast the void pointer back to shared pointer?
I have a shared pointer of objects throughout my application.我在整个应用程序中都有一个对象的共享指针。 Here is one example:
这是一个例子:
std::shared_ptr<MyTexture> texture = loadImageFromFile("someFile.png");
I am using a UI library called ImGui and this library has a concept of a texture ID, which is a void pointer.我正在使用一个名为 ImGui 的 UI 库,这个库有一个纹理 ID 的概念,它是一个 void 指针。 I am currently passing the data to this library by doing the following:
我目前通过执行以下操作将数据传递到该库:
ImGui::Image(texture.get());
And my backend stores these textures in a map that points to the Graphics API related data type (it is a Vulkan descriptor set but ) to be able to render the texture.我的后端将这些纹理存储在 map 中,它指向与图形 API 相关的数据类型(它是一个 Vulkan 描述符集但是),以便能够渲染纹理。 Now, I have one particular issue about this.
现在,我对此有一个特别的问题。 I want to manage this with a smart pointer.
我想用智能指针来管理它。 However, I am passing it as a raw pointer;
但是,我将它作为原始指针传递; so, I am not able to just wrap it in a shared pointer because the original shared pointer will be destroyed by this.
所以,我不能把它包装在一个共享指针中,因为原来的共享指针会被它破坏。 Internally, I am using shared pointers everywhere except for this one particular case.
在内部,我在任何地方都使用共享指针,除了这个特殊情况。 Is there some way that I can pass a shared pointer object itself as raw void pointer and then cast it back to shared pointer;
有什么方法可以将共享指针 object 本身作为原始 void 指针传递,然后将其转换回共享指针; so, I do not lose the shared pointer counter when passing the pointer to this function?
那么,将指针传递给这个 function 时,我不会丢失共享指针计数器吗?
No , not with std::shared_ptr
, I mean, you can get raw-pointer from smart-pointer, but you simply can't get SAME-INSTANCE of smart-pointer from raw-pointer.不,不是
std::shared_ptr
,我的意思是,您可以从智能指针获取原始指针,但您根本无法从原始指针获取智能指针的 SAME-INSTANCE。
But you can:但是你可以:
void *
" usage NEVER outlives the smart-pointer (else expect undefined-behaviour).void *
”使用永远不会超过智能指针(否则期望未定义的行为)。void *
" input (like: static MySmartPtr fromRaw(void *)
).void *
”输入找到并返回智能指针(如: static MySmartPtr fromRaw(void *)
)。std::shared_ptr
in a hash-map (like above but without custom smart-pointer implemention).std::shared_ptr
存储在哈希映射中(如上但没有自定义智能指针实现)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.