從boost library documentation我這樣說的:如何使用智能指針將對象複製爲類屬性?
概念上,智能指針被看作是擁有指向的對象, 因而負責對象的刪除時不再需要 。
我有一個非常簡單的問題:我想使用RAII作爲可複製和可分配的類的指針屬性。
複製和分配操作應該很深:每個對象都應該有自己的實際數據副本。此外,RTTI需要可用於屬性(它們的類型也可以在運行時確定)。
我應該尋找能夠複製的智能指針的實現(數據很小,所以我不需要Copy on Write指針),或者我委託複製操作我的對象的拷貝構造函數如圖this answer ?
對於可複製和賦值的類的簡單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;
}
如果您閱讀[shared_ptr]的描述(http://www.boost.org/doc/libs/1_52_0/libs/smart_ptr/shared_ptr.htm),您將看到它們是CopyConstructible和Assignable。 –
@Joachim是的,他們分享對同一個對象的引用。我需要複製操作來執行深層複製。 – tmaric
沒有使用任何智能指針的選項? –