gpt4 book ai didi

c++ - 在没有 boost 和 c++0x 的情况下安全地进行类型删除

转载 作者:太空狗 更新时间:2023-10-29 21:06:50 24 4
gpt4 key购买 nike

假设我有一个模板类

template<class T>
class A;

template<>
class A<int>
{
public:
void print(){ std::cout << "I am an int !" << std::endl; }
};

template<>
class A<double>
{
public:
void print(){ std::cout << "I am a double !" << std::endl; }
};

现在,如果我想将 A 的所有可能实例存储在同一个容器中,比如 vector 。

然后经典的(也是我知道的唯一方法)是使用纯虚拟 print() 成员函数创建另一个 A_base 类,并存储指向 A_base 的指针,该指针已初始化为 A 的实例。使用 new 执行此操作可能会引起内存泄漏并且/或异常不安全,因此解决此问题的合理方法是使用 boost::shared_ptr 或 std::tr1::shared_ptr,因为复制 std::auto_ptr 可能导致所有权问题和未定义的行为!

有没有什么方法可以在不包含 boost 或 c++0x 依赖项的情况下进行类型删除? :)

谢谢!

最佳答案

这个问题的唯一答案是“Roll your own class that already exists in Boost”,不管你喜欢ptr_vector, shared_ptr, any 等。他们已经具备了这方面的所有基础。选择你最喜欢的并推出你自己的实现,然后使用它。

编辑:一位评论者提到了 TR1。好喊。 TR1 中有 shared_ptr

关于c++ - 在没有 boost 和 c++0x 的情况下安全地进行类型删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6637744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com