In a nutshell: it's by far the most memory-efficient.
A std::string
comes with a pointer, a length, and a "short-string-optimization" buffer. But my situation is I need to store a string that is almost always empty, in a structure that I have hundreds of thousands of. In C, I would just use char *
, and it would be null most of the time. Which works for C++, too, except that a char *
has no destructor, and doesn't know to delete itself. By contrast, a std::unique_ptr<char[]>
will delete itself when it goes out of scope. An empty std::string
takes up 32 bytes, but an empty std::unique_ptr<char[]>
takes up 8 bytes, that is, exactly the size of its pointer.
The biggest downside is, every time I want to know the length of the string, I have to call strlen
on it.