Home >Backend Development >C++ >Is `&s[0]` a Safe and Contiguous Pointer to Characters in a C std::string?

Is `&s[0]` a Safe and Contiguous Pointer to Characters in a C std::string?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-05 15:41:10959browse

Is `&s[0]` a Safe and Contiguous Pointer to Characters in a C   std::string?

Can "&s[0]" Reference Consecutive Characters in a std::string?

It has been noticed that code like this:

std::string s;
s.resize( strLength );
memcpy( &s[0], str, strLength );

would be safe if s was a std::vector, but the question is whether it is a safe use of std::string.

In C 98/03, a std::string's allocation is not guaranteed to be contiguous. However, C 11 enforces this contiguity. In practice, most implementations use contiguous storage.

The use of &s[0] is guaranteed by the C 11 standard to work, even for zero-length strings. This is because the operator[] 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

Additionally, data() is defined as:

Returns: A pointer p such that p + i == &s[i] for each i in [0,size()].

Therefore, "&s[0]" points to consecutive characters in a std::string and is a safe usage.

The above is the detailed content of Is `&s[0]` a Safe and Contiguous Pointer to Characters in a C std::string?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn