When I run this C++ code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec = [&] ()
{
cout<<"pre vec.size() = "<< vec.size() <<endl;
vector<int> retval = {};
for(int i = 0; i < 10; ++i)
vec.push_back(i); // I typed "vec", not "retval"
cout<<"vec.size() = "<< vec.size() <<endl;
cout<<"retval.size() = "<< retval.size() <<endl;
return retval;
}();
cout<< vec.size() <<endl;
}
I get the output:
pre vec.size() = 34354494244
vec.size() = 10
retval.size() = 10
10
Inside the lambda, vec seems to be uninitialized first (see the size). Why does push_backing to it not cause a (valgrind) error?
After the loop, vec's size is 10, which is okay. But why does retval also already have size 10 (and not 0)?
Since I fill vec inside the lambda, but return the empty retval, why does vec have size 10 after evaluation (and not 0)?
I tried both g++ 9.3.0 and clang++ 10.0.0 and get the behavior.