I think I didn't understand the initialization of std::vector
.
The code below seems to compile and run fine with gcc, clang, and MSVC.
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{{}};
v[10] = 11; // if initialize with v{}, segmentation fault.
std::cout << "v[10]:" << v[10] << std::endl; // prints v[10]:11
for (auto e : v) // prints only v[x]:0
std::cout << "v[x]:" << e << std::endl;
}
// result:
// v[10]:11
// v[x]:0
Is accessing the element with v[10]
causing an undefined behavior?
Why does the above code with v{{}}
run fine, but not with v{}
?
Edit) Originally I didn't use the correct terminology, my fault. When I said 'not compiled', I was trying to say 'not run(after compile)'.
std::vector<int> v{};
This initializes v
as a vector of size 0
. Attempting to access any element in it results in Undefined Behavior. v[10]
is out of bounds and UB.
std::vector<int> v{{}};
This initializes v
as a vector with a single element. That single element is initialized with {}
i.e. int{}
i.e. 0
. Attempting to access any element except v[0]
results in UB. v[10]
causes UB.