For some time now I use C++11 uniform initialization syntax {}
to initialize all my variables.
Right now I want to initialize a QVector<int>
with a specific size, so I need to call the QVector(int size)
constructor (doc here).
However, QVector
also has the following constructor:
QVector(std::initializer_list<T> args)
So when I initialize my variable like this: QVector<int> foo{ 100 };
, it doesn't initialize my QVector with a size of 100 elements, but rather calls the other constructor which constructs a QVector with one element of value 100.
How can I call the QVector(int size)
constructor but still use the uniform initialization syntax?
You are trying to do the thing which is impossible. The only way to get constructor with specific size is using ()
brackets:
QVector<int> v(100);
The reason is that otherwise it would cause ambiguity. Compiler would not know what is
QVector<int> v{100};
As it is done now, it always knows this is initializer list, i.e. inserts 1 element of 100, not 100 default elements.
Pay attention, this is not Qt-specific, in STL this works the same way.