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?
When declaring
std::string cpp{};does this callnew/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 fromctocppwithout 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.
std::string's default constructor is also marked noexcept. So even if the implementation attempted to dynamically allocate in it, it would always have to have a fallback strategy because it is not allowed to propagate an allocation exception.
std::string_viewto do it without dynamic allocations. No, you cannot move anything. The original string exists in a read-only part of your program’s memory for the lifetime of your program. This is normal.const char*pointer in question is pointing at read-only memory, such as a string literal. There are plenty of legit reasons why there is a const pointer to mutable memory. There is not enough context given to make your assumption