In C++, what does a std::string own that a const char* does not, and what does copying each one cost?
answer
- owner versus address
- deep copy, own buffer
- terminator at data() + size()
- size() is stored, strlen walks
- == compares what?
basics
~20 sA std::string owns a contiguous, null-terminated buffer that it allocates, copies and frees itself; a const char* is only an address. Copying a string duplicates every character into a new buffer; copying the pointer shares the same text.
solid answer
~50 sA `std::string` is an owning value type. It holds a contiguous buffer of characters, keeps the length as a stored `size()`, guarantees a null terminator at `data() + size()`, and frees the buffer in its destructor. Copying it is a **deep copy**: the new string gets its own buffer, so the cost is linear in the length and usually one allocation, and a change to one copy never shows in the other. A `const char*` owns nothing: copying it copies an address, both names see the same characters, the length must be found with `strlen`, and somebody else decides when the memory dies. That is also why `==` on two `const char*` compares addresses while `==` on two `std::string` objects compares contents. When you need a cheap transfer rather than a copy, `std::move` hands the buffer over instead.
code
cpp · 23 lines#include <cstring>
#include <iostream>
#include <string>
int main() {
const char* literal = "/api/v1";
std::string a = literal; // copies the characters into a's own buffer
std::string b = a; // deep copy: b gets its own buffer
b += "/players";
std::cout << a << " | " << b << '\n';
std::cout << std::boolalpha
<< (a.data() != b.data()) << ' '
<< (a.size() == std::strlen(a.c_str())) << ' '
<< (a.c_str()[a.size()] == '\0') << '\n';
char raw[16];
std::strcpy(raw, literal); // a char array is just memory you manage
const char* p = raw;
const char* q = p; // copies the pointer, not the characters
raw[1] = 'A';
std::cout << q << '\n'; // sees the change made through raw
}go deeper
Say plainly that std::string owns and frees its characters while a const char* is only an address, and that == means different things for the two.
Explain the cost of a copy as a new buffer plus a linear copy, and contrast it with a constant-time noexcept move that transfers the buffer.
Show how ownership drives API shape: const std::string& or a view for readers, by-value plus move for sinks, and c_str only at the C boundary.
Frame raw char pointers as lifetime contracts the team must document and review, and std::string as the default owner that removes most of that bookkeeping.
## Two ways to hold text C++ inherited the C representation of text: an array of `char` ending in a `'\0'` byte, reached through a `const char*`. It added `std::string` (an alias for `std::basic_string<char>`), a class that manages such an array for you. The difference is **ownership**: who allocates the characters, who frees them, and what a copy means. | | `const char*` | `std::string` | |---|---|---| | what it is | an address | an object that owns a buffer | | length | found by `strlen`, a linear scan | stored; `size()` is constant time | | copy | copies the address; text is shared | copies every character into a new buffer | | `==` | compares addresses | compares characters | | who frees the text | whoever allocated it | the string's destructor | | embedded `'\0'` | ends the text | an ordinary character | ## What std::string guarantees The standard pins down a few facts that every implementation must meet: - **Contiguous storage.** `std::basic_string` is a contiguous container, so `data()[0]` through `data()[size() - 1]` are adjacent in memory, like a `std::vector<char>`. - **A null terminator.** In all cases `data() + size()` points at a character with value `'\0'`, so `c_str()` (and, since C++11, `data()`) can be handed to a C function expecting a terminated string. Overwriting that terminator with anything else is undefined behaviour. - **A stored length.** `size()` is constant time, and the string may legally contain `'\0'` characters in the middle; `size()` counts them, while a C function reading `c_str()` stops at the first one. - **Value semantics.** The copy constructor and copy assignment produce an independent string. Writing to the copy never changes the original. In C++23, `std::string s = nullptr;` no longer compiles because the `nullptr_t` constructor is deleted. Passing a `const char*` variable that happens to be null is still undefined behaviour, since the constructor computes `strlen` of it. ## What a copy costs Copying a `std::string` means: 1. allocate a buffer big enough for `size() + 1` characters (unless the text fits in a small buffer inside the object itself, the small-string optimization most libraries implement); 2. copy every character; 3. later, free that buffer when the copy is destroyed. So a copy is **linear in the length** and usually **one heap allocation**. That is why functions take text as `const std::string&` (or a view) rather than by value when they only read it, and why `std::move` matters: moving a string transfers the heap buffer to the new object in constant time and leaves the source valid but unspecified. The move constructor is declared `noexcept`. Copying a `const char*` costs a pointer copy, but it buys nothing: both names refer to the same characters, nothing is duplicated, and the pointer is only valid while whatever owns the array is alive. ## The bugs each representation invites With raw pointers the classic mistakes are: - comparing `p == q` and getting address equality instead of text equality; - returning a pointer to a local `char` array that dies with the function; - forgetting who must call `delete[]` or `free`, or calling it twice; - writing past the end of a fixed-size array with `strcpy`. With `std::string` most of those disappear, and the remaining costs are performance ones: an accidental copy in a loop, a by-value parameter, or a `std::string` built only to be passed to a function that reads it once. ## Returning text from a function Returning a `std::string` by value is the idiomatic signature, and it is cheap: `return base + path;` returns a prvalue, which C++17 constructs directly in the caller, and returning a named local is either elided or moved. Returning a `const char*` instead forces the function to answer a question its type cannot express, namely who owns the characters: - a pointer to a local `char` array dangles as soon as the function returns; - a pointer to a `static` buffer is shared by every caller, overwritten by the next call and unsafe across threads; - a pointer from `new[]` or `malloc` hands the caller a `delete[]` or `free` obligation that nothing enforces. ## Converting between them - From C to C++: `std::string s = p;` copies the characters up to the first `'\0'`; `std::string s(p, n);` copies exactly `n` characters, embedded nulls included. - From C++ to C: `s.c_str()` returns a `const char*` into the string's own buffer. It stays valid only while `s` is alive and not modified by an operation that may reallocate, so it must never outlive the string. A useful interview summary: a `std::string` is a value that owns its text, and you pay for that with a copy; a `const char*` is a reference to text that someone else owns, and you pay for that with lifetime bookkeeping.
- Why does a function that only reads text usually take const std::string& rather than std::string?A by-value `std::string` parameter copies the argument: a linear copy and usually an allocation on every call. `const std::string&` binds to the caller's string without copying. The exception is a function that keeps its own copy anyway, such as a setter: taking `std::string` by value and moving it into the member lets callers pass a temporary with a move instead of a copy.
- Can a std::string hold a '\0' character, and what happens when it is passed to a C function?Yes. `std::string` stores its length, so a `'\0'` in the middle is just a character and `size()` counts it; build such a string with `std::string(p, n)` or `append`. A C function that receives `c_str()` sees only the characters before the first `'\0'`, because C finds the end by scanning for it. Text that may contain zero bytes must travel with its length.
A std::string is a book you own: photocopying it gives you a second book you can mark up freely, at the cost of copying every page. A const char* is a note with a shelf number: copying the note is free, but every copy leads to the same book, and if its owner removes it, every note points at an empty shelf.
- Comparing two const char* with == checks whether the texts are equal.
- Copying a std::string shares the buffer, so a copy costs nothing.
- std::string::size() walks the characters like strlen does.
- A std::string cannot contain a '\0' character in the middle.
- std::string s = some_null_pointer; just produces an empty string.