我从boost库文档中读到:
从概念上讲,智能指针被视为拥有所指向的对象,并因此在不再需要该对象时负责删除它。
我有一个非常简单的问题:我想为类的指针属性使用RAII,该类是可复制和可赋值的。
复制和赋值操作应该是深层的:每个对象都应该拥有自己的实际数据副本。此外,属性需要提供RTTI(它们的类型也可以在运行时确定)。
我应该搜索一个Copyable智能指针的实现(数据很小,所以我不需要写时复制指针),还是像这个答案中所示,将复制操作委托给我的对象的复制构造函数?
我希望您能为可复制和可赋值的类选择一个简单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;
}