【问题标题】:Custom erase for c++ set or other collectionc++ 集合或其他集合的自定义擦除
【发布时间】:2016-10-19 18:16:12
【问题描述】:

我想做这样的事情:

std::set<my_type*> s;

s.insert(new my_type(...));
...
s.erase(...);

set 的擦除将删除指针以避免内存泄漏。

这对于 C++ 容器是否可行,或者正确的解决方案是将容器子类化并编写我自己的擦除,或使用某种智能指针方案?

【问题讨论】:

  • 智能指针有什么问题?
  • 智能指针没什么问题,我想知道有没有什么方法可以减少工程量。
  • set&lt;unique_ptr&lt;my_type&gt;&gt; s; s.insert (make_unique&lt;my_type&gt; (...)); 在我看来并不比你的代码更具工程性。
  • 你的意思是std::set&lt;my_type*&gt; s;,是吗?
  • @user318904 智能指针在 c++14 中,所以正如 JohnB 指出的那样,它几乎不是任何工程。标准集合类的子类是seldom the correct approach

标签: c++ design-patterns stl c++14


【解决方案1】:

您的set 被声明为存储my_type,但您发送的是my_type*,因此代码与原样不一致。无论如何,如果您不需要堆分配,请不要使用它:

std::set<my_type> s;

// Emplace improves on s.insert(my_type(...)); by allowing construction in place
// to minimize move/copy work
s.emplace(...args for my_type...);
...
s.erase(...);

在没有堆分配的情况下,您的my_type 析构函数被调用,并且它自己的结构不需要delete(或者更准确地说,set 在内部管理它)。

如果您需要堆分配,请使用智能指针,因此删除意味着释放(和std::make_unique makes this cleaner and lets you completely avoid all use of new and delete):

std::set<std::unique_ptr<my_type>> s;

s.insert(std::make_unique<my_type>(...));
...
s.erase(...);

【讨论】:

    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 2016-02-25
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多