mercredi 8 avril 2020

Why no compile error when not including initializer_list header file?

I've just see someone's blog wrote this example code, illustrating simple usage of initializer_list, appeared in C++11:

#include <iostream>
//#include <initializer_list>
using namespace std;

void print(initializer_list<int> list) {
    for(auto it = list.begin(); it!=list.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;
}

int main() {
    print({1,2,3,4,5,6,7});
    return 0;
}

However, I've tested under Ubuntu16.04 with g++-5.4 and clang++-8, also tested with Visual Studio 2017, they all compile OK, without any compile error. I wander why the commented out #include <initializer_list> is not required.

My compile command:

g++ main.cpp -std=c++11 -Wall

By not including initializer_list header file, how C++ compiler found its definition?

And also confusious, when should I enforce including initializer_list header file?

Figured out under VS2017. It's a long including.

iostream <- istream <- ostream <- ios <- xcolumn <- streambuf <- xiosbase <- xlocale <- stdexcept <- xstring <- xmemory0 <- xutility <- utility <- xstddef <- initializer_list

Aucun commentaire:

Enregistrer un commentaire