I recently realized that I can do this:
void someFunc(const std::string &str)
{
//content
}
...
someFunc("Hello World"); //this works
I'm wondering how that works and why it works.
Thanks
It works because std::string has a constructor from const char * that is not marked explicit. The C++ compiler will insert a call to one such constructor (per argument) if necessary to make the arguments match.
You example actually demonstrates the opposite: a const char array is interpreted as std::string. (BTW, a string literal is not a const char *, it is a const char[N] - a char array, not a char pointer).
The reason it work is that a char array is implicitly convertible to std::string by means of std::strings conversion constructor. The compiler performs the conversion for you, in full agreement with overload resolution rules of C++ language.
This works because the compiler creates a temporary object of type std::string in the caller, before calling someFunc().
The compiled code will be roughly equivalent to the following:
{
std::string _temp1("Hello World");
someFunc(_temp1);
}
(I put the code in braces to show that the _temp1 destructor will be executed immediately after the call to someFunc() returns.)
Your question is backwards... a const char* becomes a std::string when used as an argument, and this is because there is an implicit conversion (a constructor with one argument) from const char* to std::string.
I think you mean the reverse: 'how are const char*s interpreted as std::strings' ? Well, there is a constructor of the std::string class that converts a const char* into a std::string
An actual constructor can be found in /usr/include/c++/4.3.4/bits/basic_string.h
/**
* @brief Construct string as copy of a C string.
* @param s Source C string.
* @param a Allocator to use (default is default allocator).
*/
basic_string(const _CharT* __s, const _Alloc& __a = _Alloc());