Reputation: 8570
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
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