スマート ポインターのコンテナーに項目を追加するいくつかの方法。あなたがどの道を行くのか気になります。
class MyContainer
{
private:
std::vector<std::unique_ptr<Item>> mItems;
public:
bool Add(Item* item);
// This is Way 1
//
// Advantages:
// - Easy to add derived items, such as Add(new DerivedItem);
// - No interface change if smart pointer type changes to such as shared_ptr;
//
// Disadvantages:
// - Don't explicitly show the item to add must be allocated on heap;
// - If failed to add, user has to delete the item.
bool Add(std::unique_ptr<Item> item);
// This is Way 2
// Disadvantages and advantages are reversed from Way 1.
// Such as to add derived item, Add(std::unique_ptr<Item>(new DerivedItem));
// |
// easy to write DerivedItem here for an error
bool Add(std::unique_ptr<Item>& item);
// This is Way 3
// Similar to Way 2, but when failed to add, item still exist if it is a
// reference of outer unique_ptr<Item>
};
個人的には方法 1 を選択します。方法 2 と方法 3 の利点または方法 1 の欠点で、方法 2 または方法 3 を選択する必要があるものはありますか?
sftrabbit には多くの良い点があります。次の一般的な場合。Way 2または3を使用して簡単に行う方法は?ユーザーは、ダイアログを使用して新しい派生アイテムを生成します。装着されていstd::unique_ptr<DerivedItem> item
ます。「OK」ボタンをクリックすると、コンテナに追加されます。追加に失敗した場合は、編集のためにダイアログに戻ります。