gpt4 book ai didi

c++将对纯虚类的引用存储为类的成员

转载 作者:行者123 更新时间:2023-11-30 03:55:18 25 4
gpt4 key购买 nike

我有一个模板化包装器,其中包含一个继承纯虚拟类的类的实例。
我的问题是如何将数据存储在包装器中。
- 我不能使用拷贝,因为无法实例化纯虚拟类(如果我使用简单的虚拟类,则不能切片)。
- 我没能留下引用资料。此引用无效,因为我不管理我获得的对象的分配(超出范围)。
- 我唯一的解决方案是使用指针,即使我想避免这种情况,因为这不是很安全,我需要我的代码是健壮的。
我能做什么?

这是模拟我的问题的一个小例子:

#include <iostream>
#include <string>
#include <ctime>
#include <cmath>

using namespace std;

class Module
{
public:
Module() : m(rand())
{
cout << "m = " << m << endl;
}

virtual void f() = 0;

int m;
};

class ModuleA : public Module
{
public:
ModuleA() : ma(rand())
{
cout << "ma = " << ma << endl;
}

void f() {}

int ma;
};

template<typename T>
class Container
{
public:
Container(T e) : element(e) {}

T element;
};

// Objects are created outside of main
ModuleA createModule()
{
return ModuleA();
}

Container<Module&> createContainer()
{
return Container<Module&>(createModule());
}

int main()
{
srand((unsigned int)time(NULL));

Container<Module&> conta = createContainer();

ModuleA& ca1 = dynamic_cast<ModuleA&>(conta.element); // wrong !

system("pause");

return 0;
}

最佳答案

您可以在容器中使用 std::shared_ptr,即

template<typename T>
class Container
{
public:
// The pointer you get must be managed as well
Container(std::shared_ptr<T> e) : element(e) {}

std::shared_ptr<T> element;
};

那将是绝对安全的。实际上,如果对象超出创建它的代码的范围,您仍然有一个有效的指针,直到容器本身超出范围。如果 std::shared_ptr 的语义,您可以进一步调整与 std::weak_ptrstd::unique_ptr 的内存所有权关系不完全适合你的情况。

您绝对应该查看 std::weak_ptr,因为它允许您禁止某些代码取得指针的所有权,但仍然允许访问如果指针是在您需要访问它的位置有效。它还可以防止内存保留周期,因为 std::weak_ptr 不拥有内存。

关于c++将对纯虚类的引用存储为类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29143168/

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