Both lines create a C++ std::string named str. And both initialize them from a C string. The difference is, how they are initialized:
The first is direct initialization:
string str("Hello World");
This calls the string(const char *) constructor.
The second is copy initialization:
string str = "Hello World";
This needs that the string(const char *) constructor is non-explicit (for the previous method, the constructor can be explicit). We have a little bit differing behavior, depending on the version of the standard:
- pre C++17: first, a temporary object is created (with
string(const char *)), and then the copy (or move) constructor is called to initialize str. So, the copy (or move) constructor needs to be available. The copy constructor phase can be elided (so the object will be created just like as the direct initialization case), but still, the copy (or move) constructor needs to be available. If it is not available, the code will not compile. - post C++17: here, because the standard guarantees copy elision, only the
string(const char *) constructor is called. Copy (or move) constructor doesn't need to be available. If copy constructor is not available, the code still compiles.
So, for this particular case, there is no real difference in the end between the two initializations, and therefore, both str strings will become the same.