Accessing Contiguous Characters in std::string
One may encounter the following code in C :
std::string s; s.resize(strLength); memcpy(&s[0], str, strLength); // Is this safe?
While using &s[0] is safe in std::vector, its usage in std::string raises concerns. This article examines the safety of the presented code.
In C 98/03, a std::string's allocation was not guaranteed to be contiguous. However, C 11 mandates contiguity. In practice, all known implementations use contiguous storage.
Moreover, the C 11 standard guarantees the safety of &s[0], even for an empty string. This is because the operator[] for std::string is defined as:
Returns: *(begin() + pos) if pos < size(), otherwise a reference to an object of type T with value charT(); the referenced value shall not be modified
Furthermore, data() is defined as:
Returns: A pointer p such that p + i == &operator[](i) for each i in [0, size()].
Thus, &s[0] provides a valid pointer to the initial character of the string.
Note: Prior to standardization, accessing &s[0] for an empty string was undefined behavior. However, this has since been resolved in later standard drafts.
The above is the detailed content of Is Accessing Contiguous Characters in std::string Using `&s[0]` Safe in C ?. For more information, please follow other related articles on the PHP Chinese website!