Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stdstring

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 ?

like image 678
chenzhongpu Avatar asked Oct 26 '15 15:10

chenzhongpu


People also ask

Why do I have to use std::string?

Because the declaration of class string is in the namespace std. Thus you either need to always access it via std::string (then you don't need to have using) or do it as you did.

Is std::string the same as string?

There is no functionality difference between string and std::string because they're the same type.

What does std::string () do?

The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.

Are C strings faster than std::string?

C-strings are usually faster, because they do not call malloc/new. But there are cases where std::string is faster. Function strlen() is O(N), but std::string::size() is O(1). Also when you search for substring, in C strings you need to check for '\0' on every cycle, in std::string - you don't.


2 Answers

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.

like image 76
TartanLlama Avatar answered Sep 28 '22 19:09

TartanLlama


In short: yes, it is necessary.

Parts of standard library often use other parts, so <string> was included somehow through <iostream>, and your code compiles nicely.

If you accidentally decide that you don't need <iostream> anymore and remove that include, <string> will be implicitly removed, too, and you get a confusing compilation error. That's why it is a good practice to put all necessary includes.

like image 40
lisyarus Avatar answered Sep 28 '22 19:09

lisyarus