【问题标题】:How to avoid list.erase calling the destructor如何避免 list.erase 调用析构函数
【发布时间】:2014-08-03 15:13:33
【问题描述】:

我试图在列表中返回一个值,然后将其从列表中删除,但不删除其内容。但是当我调用list.erase 时,这个函数会调用项目的析构函数。所以项目被删除后temp的内容也被销毁了。如何保留temp的内容?

Vertice *temp = NULL;

//Remove da lista o vértice escolhido para iniciar a busca.
for (list<Vertice>::iterator it = lista.begin(); it != lista.end(); it++) {
    if (it->getId() == (v)) {
        temp = &*it;
        lista.erase(it);
        break;
    }
}

【问题讨论】:

  • 顶点的单数是“顶点”。
  • @Lightness 英语是的,但不是葡萄牙语,这似乎是代码的主要语言。

标签: c++ list destructor erase


【解决方案1】:

在调用erase之前,使用unique_ptr&lt;Vertice&gt;的列表和swap方法将对象的所有权移动到另一个指针。

【讨论】:

  • 谢谢!但首先我必须学习unique_ptr 来学习如何使用它。它的接缝太强大了。
【解决方案2】:

您可以只复制该值,而不是在擦除之前获取指向它的指针。

Vertice temp;

temp = *it;

您可以通过使用std::optional&lt;Vertice&gt; 来改进这一点,以避免先构造一个空的Vertice

【讨论】:

  • 非常感谢!我没有意识到这一点!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
  • 2013-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-12
  • 2010-11-12
相关资源
最近更新 更多