user877329
user877329

Reputation: 6220

How does std::string keep track of NUL char

C++11 guarantees that std::string stores the nul terminator internally. How can that be achieved without an explicit terminate method?

Example:

std::string foo("Baz");
printf("foo contains %s\n",&foo[0]); //Completely safe

Upvotes: 1

Views: 63

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473946

The standard requires that the string you get from data() is NUL terminated, and requires that the references generated from operator[] are contiguous and NUL terminated. That's all the specification says about it.

It is the job of the implementation to do that. Typically, this happens by just storing a NUL terminator at the end of the string, making the actual buffer size one larger than it appears. If you add characters, it still stores a NUL terminator at the end of the newly-appended-to sequence of characters. If you remove characters, it moves the NUL terminator appropriately.

This is what encapsulated types can do. They can establish and maintain invariants.

Upvotes: 4

Related Questions