acegs
acegs

Reputation: 2809

Does std::string const& parameter copies the passed const char*?

sorry if this is a very noob question. I need to to know if c++ already supported the following behavior:

void sampleFunc(std::string const& p_sVal){
    
    Log("this is your string: " + p_sVal);

}

int main(){
    
    sampleFunc("my string");   //does the param allocates a copy of "my string"...?
    
}

does the param std::string const& p_sVal allocates a copy of the passed const char* or the compiler is smart enough to know that the passed is const char* and can be optimized that it don't need to allocate and copy?

If not, can you suggest example code that achieves this? (Note: aside for string_view solution.)

Upvotes: 2

Views: 213

Answers (1)

Enlico
Enlico

Reputation: 28406

A temporary std::string is constructed, from the string literal you pass to it, for the std::string const& parameter to refer to.

As suggested in the comment, std::string owns its storage (otherwise it would be std::string_view, wouldn't it?). This observation alone, in my opinion, doesn't really tell you that the temporary std::string will not be able to steal resources from the passed argument.

The resource could be still moved, because you're passing an rvalue to sampleFun, right? No, wrong, because, as you can see here, a literal string, like "my string" in your main, is a lvalue, not an rvalue.

Oh, and even if a string literal was an rvalue, from the documentation on std::string's (well, std::basic_string's) constructor you see that there's no other constructor taking a && other then the "move constructor" (i.e. the moving version of the copy constructor, i.e. a constructor which takes the same type that it is constructing, i.e. std::string, not const char*).

Notice that since you are doing "this is your string: " + p_sVal you do want a std::string to be constructed at some point because you need std::operator+ to work. You could have sampleFunc take by const char*, but then you would have to wrap either p_sVal or the string literal in std::string{…} for + to work.

Upvotes: 2

Related Questions