If I have a function
void x(std::string const& s)
{
...
}
And I am calling it as x("abc"), will string constructor allocate memory and copy data in it?
If I have a function
void x(std::string const& s)
{
...
}
And I am calling it as x("abc"), will string constructor allocate memory and copy data in it?
The std::string constructor will be called with a const char*
argument
There is no telling whether memory would be allocated (dynamically), but the chances are that your standard library implementation has the SSO in place, which means it can store small strings without dynamic allocations.
The question is tagged with 'performance', so it's actually a good question IMO.
All compilers I know will allocate a copy of the string on the heap. However, some implementation could make the std::string
type intrinsic into the compiler and optimize the heap allocation when an r-value std::string
is constructed from a string literal.
E.g., this is not the case here, but MSVC is capable of replacing heap allocations with static objects when they are done as part of dynamic initialization of statics, at least in some circumstances.
Yes, the compiler will generate the necessary code to create a std::string
and pass it as argument to the x
function.
Constructors which take a single argument, unless marked with the explicit
keyword, are used to implicitly convert from the argument type to an instance of the object.
In this example, std::string
has a constructor which takes a const char*
argument, so the compiler uses this to implicitly convert your string literal into a std::string
object. The const reference of that newly created object is then passed to your function.
Here's more information: What does the explicit keyword mean in C++?