+ 1
What is difference between string objects
Hi I would like to understand what is difference between s and s1 in below code? #include <iostream> #include <string> using namespace std; int main() { string s = "Sololearn"; string s1 ("Sololearn"); return 0; } I believe both are constructor call and both will create temp object...Is this right or not?
1 ответ
+ 2
It is correct that both are constructor calls, and in both cases, overload resolution should choose the fifth constructor from this list:
https://en.cppreference.com/w/cpp/string/basic_string/basic_string
The main difference is that the first is copy initialization (CI), while the second is direct initialization (DI). CI is more strict because it doesn't consider explicit user-defined conversion sequences. While DI directly calls the chosen constructor, CI would first convert the const char* to a string and then perform the initialization, but this step is usually optimized out. If no optimization takes place, it would be the only scenario where a temporary object is created.
DI:
https://en.cppreference.com/w/cpp/language/direct_initialization
CI:
https://en.cppreference.com/w/cpp/language/copy_initialization
Josh Greig Unfortunately, the equals sign in CI is not related to the assignment operator (which wouldn't be implemented like that btw). Assignment operators are called for already existing objects.