加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

一个对象可以从标准的C容器中删除自己吗?

发布时间:2020-12-16 03:06:30 所属栏目:百科 来源:网络整理
导读:参见英文答案 Is delete this allowed?10个 以下代码 #include iostream#include mapstruct foo{ void kill(std::mapint,foo m,int i) { m.erase(i); }};int main(){ std::mapint,foo m; m.emplace(1,foo() ); std::cout m.size() std::endl; m[1].kill(m,1)
参见英文答案 > Is delete this allowed?10个
以下代码
#include <iostream>
#include <map>

struct foo
{
  void kill(std::map<int,foo>& m,int i)
  {
    m.erase(i);
  }
};

int main()
{
  std::map<int,foo> m;

  m.emplace(1,foo() );

  std::cout << m.size() << std::endl;

  m[1].kill(m,1);

  std::cout << m.size() << std::endl;
}

编译没有警告(g),执行没有错误,并通过输出判断kill方法从地图中删除foo对象.但是,我觉得这可能是未定义的行为.似乎在杀死方法后行m.erase(i)这不再指向一个有效的对象.

C标准对此有什么看法?

解决方法

当你输入你的kill,m [1](从m [1] .kill(m,1);)语句被完全评估为你正在调用kill的foo对象.

然后你做m.erase(i);最终破坏了当前的对象foo.

就在你从kill函数返回之前,你绝对没有使用当前对象(this)的语句,这是完全可以接受和安全的(由Auriga和Barry引用的帖子评论).即使当前对象不再存在,您的函数也将从堆栈中安全地返回,没有任何理由让我知道这样做.

作为一个例证,这将最终导致未定义的行为,并且不能完成:

struct foo
{
  void kill(std::map<int,int i)
  {
    m.erase(i);
    cout << attribute; // don't do that! current foo object does not exist anymore
  }
  int attribute;
};

所以让我们说你正在做的是有风险的,但是如果你做的很好,它是有效和安全的.

作为一个例证,这将是最终的定义的行为和可以完成:

struct foo
{
  void kill(std::map<int,int i)
  {
    int theAttribute = attribute;
    m.erase(i);
    cout << theAttribute; // OK!
  }
  int attribute;
};

有一个方法删除当前的对象可能不是一个好的做法(特别是如果另一个开发人员稍后修改代码…他可以很容易地使它与上面的第一个例子崩溃).至少在代码中给出一个明确的评论,告诉当前的对象可能已经被破坏(注意,杀死可能会破坏当前对象,另一个或没有…取决于m内容,i):

struct foo
{
  void kill(std::map<int,int i)
  {
    m.erase(i);
    // careful! current object could have been destroyed by above statement and may not be valid anymore! Don't use it anymore!
  }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读