且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

赋值运算符中的C ++函数评估顺序

更新时间:2022-10-15 17:55:49

评估顺序未指定在这种情况下。不要写这样的代码

类似的例子这里


int& foo() {
   printf("Foo\n");
   static int a;
   return a;
}

int bar() {
   printf("Bar\n");
   return 1;
}

void main() {
   foo() = bar();
}

I am not sure which one should be evaluated first.

I have tried in VC that bar function is executed first. However, in compiler by g++ (FreeBSD), it gives out foo function evaluated first.

Much interesting question is derived from the above problem, suppose I have a dynamic array (std::vector)

std::vector<int> vec;

int foobar() {
   vec.resize( vec.size() + 1 );
   return vec.size();
}

void main() {
   vec.resize( 2 );
   vec[0] = foobar();
}

Based on previous result, the vc evaluates the foobar() and then perform the vector operator[]. It is no problem in such case. However, for gcc, since the vec[0] is being evaluated and foobar() function may lead to change the internal pointer of array. The vec[0] can be invalidated after executation of foobar().

Is it meant that we need to separate the code such that

void main() {
   vec.resize( 2 );
   int a = foobar();
   vec[0] = a;
}

Order of evaluation would be unspecified in that case. Dont write such code

Similar example here