To uniformly initialize objects regardless of their type, use the brace-initialization form {} that can be used for both direct initialization and copy initialization. When used with brace initialization, these are called direct list and copy list initialization.
T object {other}; // direct list initialization
T object = {other}; // copy list initialization
Examples of uniform initialization are as follows:
- Standard containers:
std::vector<int> v { 1, 2, 3 };
std::map<int, std::string> m { {1, "one"}, { 2, "two" }};
- Dynamically allocated arrays:
int* arr2 = new int[3]{ 1, 2, 3 };
- Arrays:
int arr1[3] { 1, 2, 3 };
- Built-in types:
int i { 42 };
double d { 1.2 };
- User-defined types:
class foo
{
int a_;
double b_;
public:
foo():a_(0), b_(0) {}
foo(int a, double b = 0.0):a_(a), b_(b) {}
};
foo f1{};
foo f2{ 42, 1.2 };
foo f3{ 42 };
- User-defined POD types:
struct bar { int a_; double b_;};
bar b{ 42, 1.2 };