c++allocationstdstring

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?


Solution

  • 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:

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