std::string str;
std::string(str);
std::string str = {};
Are they the same? If no then what's the difference? And when should I use each of them?
New to C++ and trying to understand the different ways of initializing std::string.
These two declarations
std::string str;
std::string(str);
are equivalent. A declarator may be enclosed in parentheses.
Here is an example of an array declaration.
int ( ( ( a )[N1] )[N2] );
though the parentheses are redundant.
As for this declaration
std::string str = {};
then there is used the copy-initialization that requires that the default constructor would be acceptable. If it is declared as explicit (for the class std::string it is not explicit) then the compiler will issue an error.
Here is a demonstration program that produces a compiler error.
int main()
{
struct A
{
explicit A() = default;
};
A a = {};
}
If in the demonstration program to change the declaration of the object a from
A a = {};
to
A a{};
then the program will compile because in that case there will not be the copy-initialization. There will be used the direct-initialization.
As for the original declarations then they all use the default constructor of the class std::string that is not declared as explicit. So all three declarations have the same effect.
{}§ 11.6 (17.6.1) — If the initializer expression is a prvalue and the cv-unqualified version of the source type is the same class as the class of the destination, the initializer expression is used to initialize the destination object. [Example: T x = T(T(T())); calls the T default constructor to initialize x. — end example ], and your answer is ambiguous about that.
std::stringto demonstrate the many forms of initialization.