赋值运算符中的C ++函数评估顺序 [英] C++ function evaluation order in assignment operator

查看:87
本文介绍了赋值运算符中的C ++函数评估顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  INT&安培; foo(){
printf(Foo \ n);
static int a;
返回a;


int bar(){
printf(Bar\\\
);
返回1;
}

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

我不确定哪一个应该先评估。



我在VC中试过,bar函数是先执行的。然而,在g ++(FreeBSD)编译器中,它首先给出了foo函数。

很多有趣的问题都是从上面的问题得出的,假设我有一个动态数组(std :: vector)

 的std ::矢量< INT> VEC; 

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

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

根据之前的结果,vc评估foobar(),然后执行矢量运算符[]。在这种情况下这没有问题。但是,对于gcc,由于正在评估vec [0],并且foobar()函数可能会导致更改数组的内部指针。 veb [0]可以在执行foobar()后失效。



这是否意味着我们需要分离代码,使得

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


解决方案

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

类似的例子这里


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

这篇关于赋值运算符中的C ++函数评估顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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