vector<int> v;
int f()
{
v.push_back(-1);
return 1;
}
int main()
{
v.push_back(0);
cout<<v[0]<<endl;
v[0]=f();
cout<<v[0]<<' '<<v[1]<<endl;
return 0;
}
expected output:
0
1 -1
output:
0
0 1
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 150 |
vector<int> v;
int f()
{
v.push_back(-1);
return 1;
}
int main()
{
v.push_back(0);
cout<<v[0]<<endl;
v[0]=f();
cout<<v[0]<<' '<<v[1]<<endl;
return 0;
}
expected output:
0
1 -1
output:
0
0 1
Name |
---|
When evaluating
v[0]=f();
vector resizes from 1 to 2, reallocation happens, but the left-hand side address is evaluated before reallocation happens, so you perform an assignment to the memory region that is not a content of a vector any more.The order of evaluation of sides in an assignment operator is not defined, thus you have UB.
This paper "Refining Expression Evaluation Order for Idiomatic C++" was proposed for the C++17 standard. Pretty sure that it also did get accepted, so it shouldn't be UB anymore. Though I didn't find any proof other than
g++ -std=c++17
doing the expected thing.Btw, pretty funny that you are allowed to write C++ proposals in Word...
To get proof open the latest working draft based on c++17 branch n4659 and check if the changes from proposal are there. [Cppreference]http://en.cppreference.com/w/cpp/language/eval_order) is also a good source.
Yeah, should have checked it yesterday, but I was too tired.
Just for reference, the C++17 draft says: "The right operand is sequenced before the left operand." (under 8.18 Assignment and compound assignment operators)
Personally, I see no harm if it is written in Word, as long as the idea is clearly expressed :)
The following modification produces the expected output.
Global variables should be used carefully so as to avoid such unexpected side effects.
Best wishes
Thanks, it really was usefull.