函数调用作为另一个函数参数遵循任何定义的行为?

时间:2012-09-24 02:14:20

标签: c++ c++11

在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;
  }
}

2 个答案:

答案 0 :(得分:4)

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

你甚至无法做到

somefunc(i, ++i)

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

答案 1 :(得分:2)

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

  

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

您应该使用:

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

并且不再担心这些事情。

除非您能够从其他地方访问i,否则这样可以正常工作,在这种情况下,您甚至可以修复更多个问题。