Dov
Dov

Reputation: 8570

In C++11 and beyond, Is there a way to initialize a vector in an initializer list?

For a class containing a vector of strings, suppose we want a constructor which can either pass in a list or a single value. How can the second constructor call the first in an initializer list?

class A {
private:
  std::vector<const char*> paths;
public:
  A(std::vector<const char*>& paths) : paths(paths) {}
  A(const char* p) : A(std::vector<const char*>( { p } ) {}
};

The second constructor is not legal. I can't think of the syntax.

A(const char* p) : A( {p} ) {}

Not that either.

Upvotes: 0

Views: 99

Answers (1)

lukeg
lukeg

Reputation: 4399

You are creating a temporary vector, thus you should use a const reference in your first constructor:

class A {
private:
  std::vector<const char*> paths;
public:
  A(const std::vector<const char*>& paths) : paths(paths) {}
  A(const char* p) : A(std::vector<const char*>{ p }) {}
};

Alternatively, think about using r-value reference:

class A {
private:
  std::vector<const char*> paths;
public:
  A(std::vector<const char*>&& paths) : paths(std::move(paths)) {}
  A(const char* p) : A(std::vector<const char*>{ p }) {}
};

Upvotes: 1

Related Questions