lundi 13 avril 2020

C++11: how does auto deal with () initializer?

I know for C++11 way of initializing a vector using auto, actually an std::initializer_list is initialized instead of a vector. However, given below piece of code:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    auto x = {1, 2};
    cout << typeid(x).name() << endl;
    auto z = (1, 2);
    cout << z << ", type: " << typeid(z).name() << endl;
    return 0;
}

I don't understand:

  1. Why the type of x returned is St16initializer_listIiE and the type of 'z' returned is 'i', using gcc-10 compiler. Shouldn't we just return std::initializer_list and 'int'?
  2. There is a warning on z: warning: left operand of comma operator has no effect [-Wunused-value]. Then the 2nd half of result is: 2, type: i. How does c++11 interpret ()-initialized type? Why is only the last element passed into z and thus z is still of type int?

Aucun commentaire:

Enregistrer un commentaire