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
Release: 2024-12-05 15:41:10
Original
957 people have browsed it

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 );
Copy after login

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
Copy after login

Additionally, data() is defined as:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template