Peiti Peter Li Peiti Peter Li - 8 months ago 39
C++ Question

What is the curly bracket parameter in the constructor of C++11

I read an implementation of a Queue from some algorithm books, there is a snippet that is new/interesting to me which I didn't understand. I think it is something new like initialization list for vector in C++11, but I am not that confident due to the context of the code. Can anyone shed a light or provide some reference?

template <typename T>
class Queue {
size_t head, tail, count;
vector<T> data;
Queue(const size_t &cap=8) : head(0),tail(0),count(0),data({cap}) {}
//... more interfaces

the questionable part is data({cap}), what is this? It resizes the vector to a capacity of cap? (Obviously the author of the code intends to give data a size of cap when constructing it.)

after read the first answer and test, we know that the book had error in the snippet. It intends to give a initial cap, but it used erroneous {}.


That is uniform initialization, a new C++11 feature. However, it is arguably being used the right way in your example. It should be:

Queue(const size_t &cap=8) : head(0),tail(0),count(0),data(cap) {}
//                                                        ^^^^^

Because the intention is to invoke the constructor of std::vector<> that accepts the initial size of the vector. Invoking it this way:


Or this way:


Causes the constructor accepting an std::initializer_list to be picked (initializer lists are another new feature of C++11, tightly related to brace initialization), resulting in a vector initialized with one single element whose value is cap.

You can verify the above claim in this live example (code is reported below):

#include <vector>

struct X
    X(int s) : v1({s}), v2{s}, v3(s) { }
    std::vector<int> v1;
    std::vector<int> v2;
    std::vector<int> v3;

#include <iostream>

int main()
    X x(42);
    std::cout << x.v1.size() << std::endl; // Prints 1
    std::cout << x.v2.size() << std::endl; // Prints 1
    std::cout << x.v3.size() << std::endl; // Prints 42