What is the curly bracket parameter in the constructor of C++11
This question already has an answer here:
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:
data{cap}
Or this way:
data({cap})
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
}
链接地址: http://www.djcxy.com/p/70886.html