c ++ STL map :: operator []对要删除的条目执行 [英] c++ STL map::operator[] done on an entry being deleted

查看:236
本文介绍了c ++ STL map :: operator []对要删除的条目执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::map<int,int> bar;

int foo(int key)
{
  bar.erase(key);
  return 1;
}    

int main()
{
  bar[0] = foo(0);
  return 0;
}

这个代码使用GCC 4.8 segs fault。

This code compiled with GCC 4.8 segs fault when checking memory usage with electric fence.

LD_PRELOAD=libefence.so.0.0 ./a.out

问题来自编译器生成一个代码,开始在映射中分配一个新条目,然后执行foo()以获取要放入的值bar [0]。在运行foo()时,条目被销毁,代码最终通过写入未分配的内存结束。

The problem comes from the fact that the compiler generates a code that starts to allocate a new entry in the map, then executes foo() to get the value to put into bar[0]. While running foo(), the entry gets destroyed and the code finally ends by writing in non-allocated memory.

操作的排序方式取决于编译器的实现,或者是由C ++当前标准指定的?

Does the way the operations are ordered depend on the compiler implementation, or is it specified by the C++ current standard?

推荐答案

标准(§1.915) (除非在某些特定情况下):

The standard (§1.9 15) specifies that the evaluation of the two operands to a binary operator is unsequenced (unless in some specific cases):


除非另有说明,否则对单个操作符的操作数求值
和单个表达式的子表达式不被排序。

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.

这意味着它不强制赋值操作的一边另一个,事实上,它是未定义的行为,依赖于这些无序操作的顺序。

This means that it does not mandate that one side of the assignment operation is evaluated before the other, and in fact, it is undefined behavior to depend on the order of these unsequenced operations.

这通常也是真正的函数参数的评价顺序。

This is also generally true for the order of evaluation of function arguments.

您需要将您的作业分成两部分:

You need to break your assignment in two:

int result = foo(0);
bar[0] = result;

这篇关于c ++ STL map :: operator []对要删除的条目执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆