9

the following code does not compile with Visual Studio 2013 while it should:

class A
{
    A() :m_array{ 0, 1, 2 } {} // error C2536: 'A::A::m_array' : cannot specify explicit initializer for arrays
private:
    int m_array[3];
};

See bug report for more details.

What are the possible workarounds?

Korchkidu
  • 4,908
  • 8
  • 49
  • 69
  • 1
    Does initialization at the point of declaration work? `int m_array[3]{1,2,3};`? – juanchopanza Nov 09 '13 at 16:30
  • Does `std::array` work? (You'll need extra braces, unless the compiler has jumped the gun on C++14). – Mike Seymour Nov 09 '13 at 16:39
  • @juanchopanza: same error with VC++ 2013. – Korchkidu Nov 09 '13 at 17:02
  • @MikeSeymour: could you be more specific please? – Korchkidu Nov 09 '13 at 17:02
  • 2
    Declare array as `std::array m_array;` and initialize it as `A() :m_array ({ 0, 1, 2 }) {}`. Does it work or not? – masoud Nov 09 '13 at 17:12
  • This is a duplicate of the same problem found here http://stackoverflow.com/a/19659756/2694444, visual studio 2013 compiler do not support aggregate initialization in the constructor initialization list either with non static member initialization. A bug report is also alive on connect.microsoft.com, but this is more a missing feature request than a bug. – galop1n Nov 09 '13 at 17:40
  • 1
    @galop1n OP is asking for workarounds to this problem. – juanchopanza Nov 09 '13 at 20:27
  • @MM. Yes, it works now, thanks! Can you elaborate an answer on the differences between the initial code and the workarounds you and Mike proposed? – Korchkidu Nov 10 '13 at 12:48

1 Answers1

11

As the comments, you can try this workaround.

class A
{
    A() : m_array ({ 0, 1, 2 }) {}
private:
    std::array<int, 3> m_array;
};

It seems VS2013 made initializer-list for std::array constructor well and you can initialize it in constructor's intializer. The code that you wrote is valid and both gcc and clang support it. VS2013 lacks.

masoud
  • 55,379
  • 16
  • 141
  • 208
  • 4
    I had to use an extra pair of braces in the constructor for this to compile in VS2013. A() : m_array ({ { 0, 1, 2 } }) – SamuelMS Nov 18 '13 at 15:14