How to initialise a vector member variable in the class definition?
c++, c++11, uniform-initialization, visual-studio-2013, xcode5
Solution
In class member initialization is a c++11 feature making his debut in VS2013. But when the member is an aggregate, the compiler is buggy and try to use a copy constructor instead. It ignores constructors taking initializer list too and try to match the parameters only with regular constructors arguments.
A workaround, you can create a temporary vector then move with that syntax until a proper update of the compiler.
class VectorInit
{
private:
std::vector<int> m_vector { std::vector<int>{ 1, 2, 5, 7 } };
};
Problem
The following code compiles OK using XCode 5.0 but not Visual Studio 2013. ``` #include <vector> class VectorInit { private: std::vector<int> m_vector{1, 2, 3}; // fails to compile using VS 2013 }; int main() { std::vector<int> vector{1, 2, 3}; VectorInit vectorInit; return 0; } ``` This is the error that Visual Studio reports: ``` Error 1 error C2664: 'std::vector<int,std::allocator<_Ty>>::vector(std::initializer_list<int>,const std::allocator<_Ty> &)' : cannot convert argument 3 from 'int' to 'const std::allocator<_Ty> &' c:\visual studio 2013\projects\vector-init\main.cpp 6 1 vector-init ``` I haven't managed to find an example of how to initialise a vector like this in a class definition. Which compiler is correct? If the syntax is not valid, is the only option to initialise m_vector in the constructor initialiser list?