I keep hitting this weird std::vector
behavior which I can't make any sense of.
Roughly, the code looks like
#include <iostream>
#include <vector>
class MyClass{
public:
MyClass():
v_(),
w_(init_w())
{};
~MyClass()
{};
std::vector<int*> init_w()
{
v_.resize(4096);
return v_;
};
private:
std::vector<int*> w_;
std::vector<int*> v_;
};
int main()
{
MyClass a;
}
Running this gives me a bad segfault at the resize
. If a lower value is chosen for the resize
instead, the code might not segfault at all.
Update:
The problem is that, contrary to what the initializer list indicates, w_
get initialized before v_
. Hence, in init_w()
, v_
state is undefined.
Reverting the order of v_
and w_
in the declarations fixes the problem.