从boost 库文档中,我读到了这个:
从概念上讲,智能指针被视为拥有所指向的对象,因此在不再需要对象时负责将其删除。
我有一个非常简单的问题:我想将 RAII 用于可复制和可分配的类的指针属性。
复制和赋值操作应该很深:每个对象都应该有自己的实际数据副本。此外,RTTI 需要可用于属性(它们的类型也可以在运行时确定)。
我应该搜索 Copyable 智能指针的实现(数据很小,因此我不需要Copy on Write指针),还是将复制操作委托给我的对象的复制构造函数,如本答案所示?
对于可复制和可分配的类的简单 RAII,我应该选择哪个智能指针?(我认为将复制/赋值操作委托给类复制构造函数和赋值运算符的 unique_ptr 会做出正确的选择,但我不确定)
这是使用原始指针的问题的伪代码,它只是问题描述,而不是正在运行的 C++ 代码:
// Operation interface
class ModelOperation
{
public:
virtual void operate = ();
};
// Implementation of an operation called Special
class SpecialModelOperation
:
public ModelOperation
{
private:
// Private attributes are present here in a real implementation.
public:
// Implement operation
void operate () {};
};
// All operations conform to ModelOperation interface
// These are possible operation names:
// class MoreSpecialOperation;
// class DifferentOperation;
// Concrete model with different operations
class MyModel
{
private:
ModelOperation* firstOperation_;
ModelOperation* secondOperation_;
public:
MyModel()
:
firstOperation_(0),
secondOperation_(0)
{
// Forgetting about run-time type definition from input files here.
firstOperation_ = new MoreSpecialOperation();
secondOperation_ = new DifferentOperation();
}
void operate()
{
firstOperation_->operate();
secondOperation_->operate();
}
~MyModel()
{
delete firstOperation_;
firstOperation_ = 0;
delete secondOperation_;
secondOperation_ = 0;
}
};
int main()
{
MyModel modelOne;
// Some internal scope
{
// I want modelTwo to have its own set of copied, not referenced
// operations, and at the same time I need RAII to for the operations,
// deleting them automatically as soon as it goes out of scope.
// This saves me from writing destructors for different concrete models.
MyModel modelTwo (modelOne);
}
return 0;
}