Original Post
If I pass a constant string literal to a function, and it takes an std::string, will that create a temporary std::string object with the cost of a memory allocation and release by new and delete respectively, as well as the cost of a copy operation? Example: If the parameter is declared as a const char *, it's obvious that there will be no such memory allocation, and if I really need to pass an std::string I can do so with c_str(). Using std::string as parameter will, by a plain translation, result in a copy operation, but a clever compiler should optimize that away in my opinion. Are compilers that clever, or is const char * a better alternative if I need to be absolutely sure there's no unnecessary copying and allocation taking place? How can I find out? I'm using Visual C++ and GCC. Note I may be using more complex indirect passing of the parameter through several nested function calls etc., and another interesting case is if I use an old API which returns a dynamically allocated char * and I need to pass it to a method for reading. In which cases, if any, will using std::string as parameter lead to invocation of new and delete calls which can't be optimized away by the compiler?
void f(const std::string& s) {
std::cout << s;
}
int main() {
f("Hello world!");
}