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

Do function calls as another functions parameters follow any defined behaviour?

本文关键字:任何 定义 参数 是否 另一个 函数 函数调用      更新时间:2023-10-16

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

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

你甚至不能做

somefunc(i, ++i)

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

未指定函数参数的计算顺序。 C++11 5.2.2.Function call para/4指出:

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

您应该使用:

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

不要再担心这些事情了。

除非您能够从其他地方访问i,否则这将正常工作,在这种情况下,您有更多应该修复的问题。

相关文章: