C++ Initializer-List Constructors | `std::initializer_list` Ctors Explained
이 글의 핵심
An initializer_list constructor lets your type initialize from `{a,b,c}`. It takes precedence for brace syntax over many other ctors—know the priority rules and lifetime of the backing array.
What is an initializer-list constructor?
A constructor that takes std::initializer_list<T> lets users write:
#include <initializer_list>
#include <vector>
class MyVector {
std::vector<int> data;
public:
MyVector(std::initializer_list<int> list) {
for (int x : list) data.push_back(x);
}
};
int main() {
MyVector vec = {1, 2, 3, 4, 5};
}
Priority over other ctors
class MyClass {
public:
MyClass(int x) {
std::cout << "int ctor: " << x << "\n";
}
MyClass(std::initializer_list<int> list) {
std::cout << "initializer_list ctor\n";
}
};
int main() {
MyClass a(10); // int ctor
MyClass b{10}; // initializer_list ctor
MyClass c = {10}; // initializer_list ctor
}
Empty braces vs empty list
class MyClass {
public:
MyClass() { std::cout << "default\n"; }
MyClass(std::initializer_list<int> list) { std::cout << "list\n"; }
};
int main() {
MyClass x; // default
MyClass y{}; // default
MyClass z{{}}; // initializer_list (empty)
}
How it works
The compiler typically allocates a const temporary array for {1,2,3} and passes pointer + length to initializer_list. Do not store an initializer_list past the full-expression unless you copy into a vector. Copies of initializer_list alias the same array.
Relation to std::vector
vector(n, val)vsvector{n, val}— different ctors (size/fill vs two-element list).- Custom types with both (int,int) and
initializer_listneed clear conventions.
Performance notes
- Passing
initializer_listis cheap; populating avectorfrom it may allocate. - Prefer range ctor or reserve when you know sizes upfront.
FAQ
Q: When to use?
A: APIs that take “list of values” with homogeneous type.
Q: Modifiable?
A: View is read-only—copy if you need to mutate.
Resources: Effective Modern C++, cppreference.
Related posts
- C++ initializer_list
- C++ explicit keyword
Keywords
C++, initializer_list constructor, overload resolution, braced init, C++11.
More links
- C++ explicit keyword
- C++ default and delete