Boostライブラリのドキュメントから私はこれを読みました:
概念的には、スマートポインターは、ポイントされたオブジェクトを所有していると見なされるため、オブジェクトが不要になったときにオブジェクトを削除する責任があります。
非常に単純な問題があります。コピー可能で割り当て可能なクラスのポインター属性にRAIIを使用したいのです。
コピーと割り当ての操作は深くする必要があります。すべてのオブジェクトには、実際のデータの独自のコピーが必要です。また、属性に対してRTTIを使用できる必要があります(属性のタイプは実行時に決定される場合もあります)。
コピー可能なスマートポインターの実装を検索する必要がありますか(データが小さいため、コピーオンライトポインターは必要ありません)、またはこの回答に示すように、コピー操作をオブジェクトのコピーコンストラクターに委任しますか?
コピー可能で割り当て可能なクラスの単純な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;
}