Reputation: 101
I read the C++ Primer and it is said when we use a '=' operator, or when a function parameter is a value of a class type or a function return type is a value of a class type, c++ will use what's called "copy initialization", which different with "direct initialization" that find the corresponding constructor based on parameter, "copy initialization" will use the "copy constructor". So in the following code, when I supplies "hello" as the argument to Foo, it should use the copy constructor, which is string (const string& str) to initialize the parameter. But my argument is "hello", which is a const char *, so what actually happened for the const char * to become a valid argument for the const string & parameter? Could some one give more detailed information? Thanks!
void Foo(string str){}
int main() {
Foo("hello");
}
Upvotes: 0
Views: 1363
Reputation: 119124
The initialization of str
in the above code has the same semantics as the following:
string str = "hello";
This is indeed what is called copy initialization. Assuming that string
is std::string
, there exists a constructor taking a single argument of type const char*
, that is, string::string(const char*)
. This constructor will be invoked for the initialization. Calling this constructor creates a temporary of type string
. Then the copy or move constructor of string
is called to initialize str
from the temporary. Typically, the extra copy or move is elided, and neither the copy nor move constructor is called at all, despite the name "copy initialization".
Upvotes: 5