How to initialize a member variable of a vector in a class definition?

The following code compiles 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 could not find an example of how to initialize such a vector in the class definition.

Which compiler is right?

If the syntax is invalid, is the only option to initialize m_vector in the constructor initialization list?

+6
source share
2 answers

The initialization of a class member uses the C ++ 11 function, which will debut in VS2013. But when the member is an aggregate, the compiler does not work correctly and instead tries to use the copy constructor. It ignores constructors, which also take a list of initializers and try to match parameters only with regular constructor arguments.

Workaround, you can create a temporary vector, and then move with this syntax until the corresponding compiler update.

 class VectorInit { private: std::vector<int> m_vector { std::vector<int>{ 1, 2, 5, 7 } }; }; 
+7
source

How to initialize a member variable of a vector in a class definition (C ++ 11)

What you do is right. It initializes the data member to have the values 1, 2, 3 whenever you create an instance of VectorInit .

However, if you need another constructor that requires () , you need an alternative syntax:

 std::vector<int> m_vector = std::vector(5, 42); // five elements set to 42 

Which compiler is right?

The syntax is valid C ++, so non-VS compilers are right.

If your compiler does not support this type of initialization, you can add a constructor to your class as a workflow:

 class VectorInit { public: VectorInt() : m_vector{1, 2, 3}{} private: std::vector<int> m_vector; }; 
+4
source

All Articles