1

在 C++11 中是否有关于以下内容的任何已定义行为?(即 a = 1、2 或未定义)

void somefunc(int a, int b) {
  std::cout << a << b << std::endl;
}

int i = 0;
somefunc(++i, ++i)

或者我应该写:

int i = 0;
int a = ++i;
int b = ++i;
somefunc(a, b);

我问的原因是我正在解析一个文件的选项,在一种情况下我想创建一个键值对。并具有类似于以下的功能:

std::string create_key(std::string &source, size_t &size, int &index) {
  std:: string key = "";
  while(index < size) {
    // parse the string to create the key
    ++index
  }
  return key;
}

// Value is an base class for a template class. Allowing me to store values 
// of different data types inside a container.
Value* create_value(std::string &source, size_t &size, int &index) {
  Value* value = nullptr;
  while(index < size) {
    // determine type and assign it to value
    ++index;
  }
  return value;
}

std::map<std::string, Value*> create_object(std::string &source, size_t &size, int &index) {
  std::map<std::string, Value*> object;
  while(index < size) {
    // the line I think produces the same issue as my original example
    object.insert(std::pair<std::string, Value*>(create_key(source, size, index), create_value(source, size, index)));
    ++index;
  }
}
4

2 回答 2

4

是的,因为您正在以相对于同一变量的另一个修改没有顺序的方式修改变量。请注意,逗号不是逗号运算符,它会引入排序并防止 UB;它只是分隔函数参数。

你甚至不能做

somefunc(i, ++i)

不会导致未定义的行为。修改变量,然后分别调用函数(或者如果它是你想要的,反之亦然)。

于 2012-09-24T02:24:11.230 回答
2

未指定评估函数参数的顺序。C++11 5.2.2.Function call para/4状态:

调用函数时,每个参数都应使用其对应的参数进行初始化[注意:此类初始化相对于彼此的顺序是不确定的]。

你应该使用:

somefunc (i+1, i+2); i += 2;

并停止担心这些事情。

除非您能够i从其他地方访问,否则这将正常工作,在这种情况下,您还有更多问题需要解决。

于 2012-09-24T02:28:12.157 回答