Geoffrey Hoffmann
Geoffrey Hoffmann

Reputation: 155

std::vector with size and value constructor fails to compile under MSVC 16.9

Here is a minimal reproducible example of a problem I am having with std::vector and MSVC

#include <iostream>
#include <vector>
#include <string>

using namespace std;    // For brevity

struct Struct
{
    vector< int > Values(6, 0);         // Should hold 6 zeros
    vector< int > NormalConstructor;    // Example of normal vector

    void Dump() { for (auto val : Values) { cout << val << " "; } }
};

int main()
{
    Struct s;

    s.Dump();

    cout << "\n";
}

The line vector< int > Values(6, 0); results in error C2059: syntax error : 'constant', and the variable named Value is being coloured as though it is a function declaration.

Screenshot

cppreference.com says this constructor "3) Constructs the container with count copies of elements with value value"

There are several questions on here along these lines that I have looked at, but none seem to indicate what is wrong, or what I should do to avoid this error.

What should I be doing instead ?

Upvotes: 0

Views: 106

Answers (1)

songyuanyao
songyuanyao

Reputation: 172984

Parentheses initializer can't be used to initialize data member in default member initializer (since C++11). (The compiler is trying to interprete it as function declaration.)

You can use euqal-sign initializer instead.

struct Struct
{
    vector< int > Values = vector< int >(6, 0);  // Should hold 6 zeros
    vector< int > NormalConstructor;             // Example of normal vector

    void Dump() { for (auto val : Values) { cout << val << " "; } }
};

Or use member initializer list in constructor.

struct Struct
{
    vector< int > Values;
    vector< int > NormalConstructor;             

    void Dump() { for (auto val : Values) { cout << val << " "; } }

    Struct() : Values(6, 0) {}
};

Upvotes: 4

Related Questions