を、スマートポインタは、それがもはや が必要なときにオブジェクトが 、指さないので、オブジェクトの削除に責任を所有すると見られています。
私は非常に単純な問題があります。コピー可能で割り当て可能なクラスのポインタ属性にRAIIを使用したいと考えています。
コピー操作と割り当て操作は深くなければなりません。すべてのオブジェクトには、実際のデータのコピーが必要です。また、RTTIは属性に対して使用可能である必要があります(そのタイプは実行時にも決定される可能性があります)。
コピー可能なスマートポインタ(データは小さいので、Copy on Writeポインタは必要ありません)の実装を検索するか、コピー操作をthis answerのようにオブジェクトのコピーコンストラクタに委譲しますか?
コピー可能で割り当て可能なクラスの単純なRAIIに対して、どのスマートポインタを選択しますか? 、
はここで生のポインタを使用して問題の擬似コードだ(私はクラスのコピーコンストラクタと代入演算子への委任のコピー/割り当て操作とunique_ptrを、適切な選択をするだろうと考えていますが、私はわかりません)私はすぐに使用を実現について聞いたことがありませんが、あなたは単に自分でそれを行うことができます
// 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
オプションでスマートポインタを使用していませんか? –