The syntax of the initializer list in the member initializer list (C ++ 11)

I went through A Tour of C ++ ', and Bjarne uses the C ++ 11 initializer list function when initializing members to a constructor like this (using curly braces):

A a;
B b;
Foo(Bar bar):
  a{bar.a}, b{bar.b}
{}

This, however, does not compile until C ++ 11. What is the difference with the old list of member initializers (using parentheses):

Foo(Bar bar):
  a(bar.a), b(bar.b)
{}

So what is the difference and when you need to be preferable to another?

+3
source share
3 answers

So what is the difference?

Parentheses only work for non-class types or types with a suitable constructor for the number of arguments in brackets.

, - struct . :

struct {
    int a,b;
} aggregate;
int array[2];

Foo() : aggregate{1,2}, array{3,4} {}

, initializer_list, (), . :

std::vector<int> v1;
std::vector<int> v2;

Foo() :
    v1(10,2),   // 10 elements with value 2
    v2{10,2}    // 2 elements with value 10,2
{}

?

, , , initializer_list; .

, , ; , " ".

, , .

+8

:

std::vector<int> v{3, 2}; // constructs a vector containing [3, 2]
std::vector<int> u(3, 2); // constructs a vector containing [2, 2, 2]

, , v u , .

, std::initializer_list<T> , , .

+2

: , . , , , , , :

  • , , , , , - .
  • , std::initializer_list<T> / . std::initializer_list<T> ( T), .

, std::initializer_list<T>, - . std::initializer_list<T>.... , , , .

0

Source: https://habr.com/ru/post/1659220/


All Articles