Can std::string be used without #include <string>?

chenzhongpu picture chenzhongpu · Oct 26, 2015 · Viewed 7.3k times · Source

Here is my code:

#include <iostream>

int main(int argc, char const *argv[])
{
    std::string s = "hello";
    std::cout << s.size() << std::endl;
    return 0;
}

To my surprise, I can compile and run it with clang++, though I even don't add #include <string>.

So, is it necessary to add #include <string> in order to use std::string ?

Answer

TartanLlama picture TartanLlama · Oct 26, 2015

Your implementation's iostream header includes string. This is not something which you can or should rely on. If you want to use std::string, you should always #include <string>, otherwise your program might not run on different implementations, or even in later versions of your current one.