0

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?

4

4 回答 4

4

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.

SSO: Meaning of acronym SSO in the context of std::string

于 2012-05-14T17:00:01.030 回答
2

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.

于 2012-05-14T16:58:15.163 回答
1

Yes, the compiler will generate the necessary code to create a std::string and pass it as argument to the x function.

于 2012-05-14T16:50:29.457 回答
0

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++?

于 2012-05-14T16:54:21.793 回答