c++ - 指向不同类的共享指针数组

标签 c++ c++11 shared-ptr smart-pointers

我试图弄清楚是否可以创建一个指向不同类型的共享指针数组。 例如,类似这样的:

vector<shared_ptr<**???**>> v;
v.push_back(shared_ptr<int>(new int));
v.push_back(shared_ptr<MyClass>(new MyClass()));

或任何其他方式在不知道其类型的情况下传递 shared_ptr

最佳答案

更多类型安全可能是:

/// header #include <boost/variant.hpp>
typedef boost::variant < boost::shared_ptr < T1 >, boost::shared_ptr < T2 >, ... > VariantT;

std::vector < VariantT > container;
container.push_back ( boost::shared_ptr < T1 > ( new T1 ) ); // or boost::make_shared
container.push_back ( boost::shared_ptr < T2 > ( new T2 ) ); // or boost::make_shared

更多请看Boost.Variant library .

关于c++ - 指向不同类的共享指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26843024/

相关文章:

c++ - 构建本身就是 shared_ptr 类型的模板化容器

android - 获取 AIMAGE_FORMAT_JPEG 图像失败

c++ - 从单独的文件中读取每个字符?

c++ - 循环直到没有遇到 std::vector 的任何元素

c++ - 在将 unique_ptr 移动到同一对象的基类构造后,使用指向对象的原始指针初始化字段

c++ - boost::shared_ptr parent <-> child 通信

c++ - 在 C++11 智能指针中存储 std::thread

c++ - 仅使用 g++ 有效,但不能使用 "g++ -c"和 ld

c++ - 使用 MSVC 在模板函数中调用用户定义的转换运算符的正确方法

c++ - Visual Studio 2013 Update 2 中的 C++ 改进是什么?