Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempting to use vector's fill constructor in class member initialization fails. What is wrong?

When using std::vector's fill constructor (either form) with C++11's class member initialization feature, the following code fails to compile (under clang/llvm 3.6):

#include <vector>

class Foo
{
  std::vector<char> buf_(10); //compiler error!
  std::vector<std::vector<char>> buf2_(10, std::vector<char>(20)); //compiler error!

public:
  void Bar();
};

void Foo::Bar()
{
  std::vector<char> buf3_(10); //OK
  std::vector<std::vector<char>> buf4_(10, std::vector<char>(20));  //OK
}

I've searched for issues around vector fill constructors and class member initialization, but have come up empty. Any idea what am I missing?

like image 682
U007D Avatar asked Jan 28 '26 12:01

U007D


1 Answers

In-place initialization of non-static data members is not allowed using that syntax. You need the form

T t{args}; // 1

or

T = t{args}; // 2

or

T = t(args); // 3

The reason is to avoid anything that could look like a function declaration.

Also note that for std::vector form 1 may lead to some surprising behaviour, because the initialization list constructor takes precedence. So

std::vector<int> v{1,2}; // two elements: 1 and 2

is not the same as

std::vector<int> v = std::vector<int>(1, 2); // 1 element: 2
like image 51
juanchopanza Avatar answered Jan 30 '26 02:01

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!