SpeakX
SpeakX

Reputation: 385

std::string from const char* with zero allocation

When declaring std::string cpp{}; does this call new/malloc?

Assume we already have a const char* c. Is it possible to move the contents from c to cpp without extra allocations?

Upvotes: 1

Views: 126

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597906

When declaring std::string cpp{}; does this call new/malloc?

That depends on the particular std::string implementation, but likely not. Nothing stops the implementation from providing a default capacity dynamically, but like most things in C++, you don't pay for what you don't need, so they likely will not preallocate dynamic memory on a default-constructed string. Especially if Short String Optimization (SSO) is implemented.

Assume we already have a const char* c. Is it possible to move the contents from c to cpp without extra allocations?

Move, never. std::string can only ever move from another std::string object.

In the case of a const char*, std::string will always copy the characters into its own memory.

Whether or not that copy will allocate memory dynamically depends on 2 factors:

  • whether or not std::string implements SSO. Most vendors do nowadays.

  • whether or not the content of the const char * fits entirely inside the SSO buffer, if implemented.

If both conditions are true, then no memory is allocated dynamically. Otherwise, memory is allocated dynamically.

Upvotes: 8

Related Questions