Question

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?

Was it helpful?

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 } };
};

OTHER TIPS

How to initialise a vector member variable in the class definition (C++11)

What you are doing is correct. It initializes the data member to have values 1, 2, 3 whenever you instantiate a VectorInit.

However, if you needed a different constructor which requires(), then you need an alternative syntax:

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

Which compiler is correct?

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

If your compiler does not support this type of initialization, you could add a constructor to your class as a work-around:

class VectorInit
{
public:
  VectorInt() : m_vector{1, 2, 3}{}
private:
    std::vector<int> m_vector;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top