Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does brace initialization in C++ solve the problem of initialization of STL containers?

Tags:

c++

I'm reading Effective Modern C++, in the section about brace initialization.

Even with several initialization syntaxes, there were some situations where C++98 had no way to express a desired initialization. For example, it wasn’t possible to directly indicate that an STL container should be created holding a particular set of values (e.g., 1, 3, and 5)

Then he shows:

std::vector<int> v{ 1, 3, 5 }; // v's initial content is 1, 3, 5

Why wasn't it possible to do

std::vector<int> v(1,3,5) 

before? How is the constructor of a class that accepts brace initialization different?

like image 389
Guerlando OCs Avatar asked Sep 09 '19 14:09

Guerlando OCs


2 Answers

In order to implement

std::vector<int> v(1,3,5);

, the C++98 standard library implementers would have had to provide a constructor with an arbitrarily long argument list, and the presence of the constructor to set the number of elements of a given value, and the ability to change the allocator would have been a further complications. A maximum argument limit would have had to been agreed upon. It could have also been ambiguous if you wanted a vector of allocators! All this means the idea would have been objectionable.

The constructor facilitating modern day list initialisation uses a special initialiser list object.

like image 59
Bathsheba Avatar answered Oct 13 '22 11:10

Bathsheba


Why it wasn't possible to do

std::vector<int> v(1,3,5) 

Because vector didn't have a constructor that would accept 3 elements.

It would not have been practical to define a constructor for every possible number of elements to initialise. Especially since some number of arguments are ambiguous with other constructors: Single integer constructs a vector of certain size, and one integer and one element copy initialises those elements.

The introduction of std::initializer_list and its special role in the extended list initialisation in C++11 made std::vector<int> v{ 1, 3, 5 } possible.

How different is the constructor of a class that accepts brace initialization?

In case of vector, the declaration looks like this:

vector(std::initializer_list<T> init,
    const Allocator& alloc = Allocator() );
like image 33
eerorika Avatar answered Oct 13 '22 11:10

eerorika