use*_*020 5 c++ containers smart-pointers unique-ptr
在智能指针容器中添加项目的几种方法.我想知道你会选择哪种方式.
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>
};
Run Code Online (Sandbox Code Playgroud)
我个人选择的方式1.方式2和方式3的任何更多优点或方式1的缺点,我应该去2或3?
sftrabbit给出了很多好处.在以下常见情况中.如何使用方式2或3轻松完成?用户使用对话框生成新的派生项.它被戴上了std::unique_ptr<DerivedItem> item.单击"确定"按钮时,会将其添加到容器中.如果添加失败,请返回对话框进行编辑.
我投票支持:
bool Add(std::unique_ptr<Item> item);
Run Code Online (Sandbox Code Playgroud)
原因:
从函数签名中可以清楚地看出客户端需要将对象的所有权传递给MyContainer.如果您选择选项1,则仍然不清楚客户端delete本身是否应该是对象本身,或者即使它们应该传递动态分配的对象.
如果客户std::move已经拥有由命名管理的对象,则客户被迫明确转移所有权std::unique_ptr.他们不会意外失去所有权.选项3没有明确表示它将取得所有权.
当我们有std::make_unique(N3588)时,添加元素的方法将是:
container.Add(std::make_unique<Item>());
Run Code Online (Sandbox Code Playgroud)
这避免new了在某些情况下使用和改善异常安全性.
您为派生对象提供的问题并不是真正的问题.如果你做错了,你会得到一个编译时错误.
如果界面更改为使用不同类型的智能指针,则客户端将需要知道.他们不想继续传递认为他们通过所有权的对象,如果实际上他们正在共享它.他们特别想知道相反的情况.
| 归档时间: |
|
| 查看次数: |
309 次 |
| 最近记录: |