我有可以包含指向某些数据及其数据类型的指针的类。因此,每时每刻我都可以使用强制转换为适当类型的数据来处理这些数据。
这是int和float的示例:
enum MyType {
NO_TYPE,
INT,
FLO
};
class MyClass {
public:
MyType type;
void* data;
MyClass(int i)
:
type(MyType::INT)
{
data = (void*) new int(i);
}
MyClass(float i)
:
type(MyType::FLO)
{
std::cout << "Constructor\n";
data = (void*) new float(i);
}
MyClass()
:
type(MyType::NO_TYPE)
{
std::cout << "Constructor (default)\n";
data = nullptr;
}
void Copy(const MyClass &from)
{
this->type = from.type;
if (this->type == MyType::INT)
this->data = (void*) new int (*((int*)from.data));
if (this->type == MyType::FLO)
this->data = (void*) new float (*((float*)from.data));
}
MyClass(MyClass &from) {
std::cout << "Copy constructor\n";
Copy((const MyClass&)from);
}
MyClass(const MyClass &from) {
std::cout << "Copy constructor\n";
Copy(from);
}
~MyClass() {
std::cout << "Destructor for type " << this->type << "\n";
if (this->type == MyType::INT)
delete (int*)this->data;
if (this->type == MyType::FLO)
delete (float*)this->data;
this->data = nullptr;
}
};
Run Code Online (Sandbox Code Playgroud)
我想用重写它shared_ptr。但是我的主要问题data是void*。有一些技巧可以帮助我吗?
更新:
编写此类的主要目的是将一些不同的数据存储在一个队列中,例如queue<MyClass>
我不能说说使用a的价值shared_ptr<void>,但是它可以用作指针的通用容器。
这些是有效的:
int i = 42;
std::shared_ptr<void> spVoid = std::make_shared<int>(i);
float f = 3.14f;
std::shared_ptr<void> spVoid = std::make_shared<float>(f);
Run Code Online (Sandbox Code Playgroud)
当最后一个引用消失时,将调用对原始实例化项目的正确析构函数。通过类实例自己查看。
struct Foo
{
Foo()
{
std::cout << "Foo constructor" << std::endl;
}
~Foo()
{
std::cout << "Foo destructor" << std::endl;
}
};
int main()
{
std::shared_ptr<void> spVoid = std::make_shared<Foo>();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我向上传播shared_ptr的唯一警告是关于跨越DLL边界。如果在DLL或共享库单元之间传递了shared_ptr实例,则原始类型(和正确的析构函数)可能会丢失。