2

I'd like to use boost::any as a universal type to store in a container and to pass to different functions. But inside these functions I always know the real type, so in runtime I don't need any type safety checks and the imposed overhead, static_cast is enough.

The ideal solution would be to use something like boost::polymorphic_downcast, but as I can see it can't be applied in this case.

Should I just write my own wrapper for void* or is there another option?

4

1 回答 1

1

您可以使用shared_ptr<void>或 unique_ptrstatic_cast来替换boost::any,与原始指针shared_ptr<void>相比有几个优势,例如:void*

  • 自动删除其存储
  • 可以在你的代码中被多个对象引用(可能你不需要这个)

但是当然在这种情况下,每个指针都需要更多内存(用于引用计数和删除器)。

如果共享对您不利,并且您的对象将仅在您也可以使用的容器中拥有unique_ptr<void>

于 2013-05-22T14:53:55.880 回答