user1899020
user1899020

Reputation: 13575

Anyone give me an example to use QVector::QVector(std::initializer_list<T> args)?

Anyone give me an example to use the following constructor int Qt?

QVector::QVector(std::initializer_list<T> args);

Upvotes: 7

Views: 14025

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110748

A constructor that takes an std::initializer_list is considered when you use list-initialization. That's an initialization that involves a braced initialization list:

QVector<int> v{1, 2, 3, 4, 5};
// or equivalently
QVector<int> v = {1, 2, 3, 4, 5};

Note that this is a C++11 feature. In fact, the first syntax is new to C++11, while the second could have been used in C++03 for aggregate initialization.

You can also use direct-initialization and pass the initializer list as the argument:

QVector<int> v({1, 2, 3, 4, 5});

Since the constructor is not explicit, it can also be used in some other interesting ways:

  1. Passing a QVector argument:

    void foo(QVector<int>);
    
    foo({1, 2, 3, 4, 5});
    
  2. Returning a QVector:

    QVector<int> bar()
    {
      return {1, 2, 3, 4, 5};
    }
    

§8.5.4 List-initialization [dcl.init.list]:

A constructor is an initializer-list constructor if its first parameter is of type std::initializer_list<E> or reference to possibly cv-qualified std::initializer_list<E> for some type E, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

§13.3.1.7 Initialization by list-initialization [over.match.list]:

When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases:

  • Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of the initializer list as a single argument.

  • [...]

Upvotes: 11

Related Questions