I'm trying to understand how addition of std::string to char* works. This code is compiling and working just as expected:
#include <string>
#include <cstdio>
void func (const char* str) {
printf("%s\n", str);
}
int main () {
char arr[] = {'a','b','c',0};
char *str = arr;
func((str + std::string("xyz")).c_str()); // THIS LINE
return 0;
}
Run Code Online (Sandbox Code Playgroud)
But I do not understand what constructors/methods is calling and in what order for this to work. This is addition of std::string to char* which gives another std::string, but char* is not a class and it does not have a addition operator.
You are using operator + for const char* on the left hand side and a temporary std::string on the right hand side. This is overload #4 here:
Run Code Online (Sandbox Code Playgroud)template< class CharT, class Traits, class Alloc > basic_string<CharT,Traits,Alloc> operator+( const CharT* lhs, const basic_string<CharT,Traits,Alloc>& rhs );Return value
A string containing characters from lhs followed by the characters from rhs
With std::string and char, the above template signature can be "interpreted" as
std::string operator+ (const char* lhs, const std::string& rhs);
Run Code Online (Sandbox Code Playgroud)
The result is a new, temporary std::string object that owns the concatenated new buffer "abcxyz". It can bind to the function argument of type const char* and is valid as long as the function body executes.