使用std :: shared_ptr< void>指向任何东西 [英] Using std::shared_ptr<void> to point to anything

查看:1807
本文介绍了使用std :: shared_ptr< void>指向任何东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用 std :: shared_ptr< void> 创建一个智能指针,可以指向许多不同类型的数据结构,如结构,向量,矩阵...基本上任何东西。我要做的是将一些名称映射到他们的数据结构。



我使用hashtable执行映射:



std :: unordered_map< std :: string,std :: shared_ptr< void>>



我可以将 find()返回的 std :: shared_ptr< void> $ c> std :: shared_ptr< my_type> ?如果是,如何?



更重要的是,这是好的做法吗?这将增加复杂性太多,因为应用程序的规模?或者,有没有其他完全不同的,优雅的方法?



EDIT



可能不能使用`Boost.Any',因为它使用RTTI。



也不能对所有这些数据结构使用基类,因为它们中的一些是STL容器,如 std :: vector



关于 shared_ptr 在下面的答案,我读到shared_ptr执行类型擦除,并且存储类型信息,以知道调用哪个析构函数。



共享void指针。为什么会这样?



为什么std :: shared_ptr< void>工作



为什么是shared_ptr< void>

解决方案



/ div>

这不是好的做法。如果您不在 std :: shared_ptr 旁边存储其他类型信息(您可以使用 static_pointer_cast )你有未定义的行为。也许 Boost.Any 是您的选择吗? / p>

如果你想坚持使用 std :: shared_ptr< void> ,请记住提供一个自定义删除函数 make shared_ptr不使用删除)。


I'm using a std::shared_ptr<void> in my application to make a smart pointer which can point to many different types of data structures like structs, vectors, matrices... basically anything. What I'm trying to do is map some names to their data structures.

I'm performing the mapping using a hashtable:

std::unordered_map<std::string, std::shared_ptr<void>>

Can I cast the std::shared_ptr<void> returned by find() back to std::shared_ptr<my_type>? If so, how?

More importantly, is this good practice? Will this increase the complexity too much as the application scales? Or, is there some other completely different, elegant approach?

EDIT

Probably cannot use `Boost.Any' since it uses RTTI.

Also cannot use a base class for all these data structures, since some of them are STL containers like std::vector.

About the shared_ptr delete issue discussed on an answer below, I read that shared_ptr performs type erasure and does store type information to know which destructor to call.

Shared void pointers. Why does this work?

Why do std::shared_ptr<void> work

Why is shared_ptr<void> not specialized?

But I'm not sure about this.

解决方案

This is not good practice. If you don't store additional type information next to your std::shared_ptr (which you can cast using static_pointer_cast) you have undefined behaviour all around. Maybe Boost.Any is an option for you?

If you want to stick with std::shared_ptr<void> please remember to provide a custom deleter function (see make shared_ptr not use delete).

这篇关于使用std :: shared_ptr&lt; void&gt;指向任何东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆