I'm doing some maintenance work and ran across something like the following:
std::string s; s.resize( strLength ); // strLength is a size_t with the length of a C string in it. memcpy( &s[0], str, strLength );
I know using &s[0] would be safe if it was a std::vector, but is this a safe use of std::string?
present tense third-person singular of do.
Does references the performance or achievements of another. An example of does is telling a friend that your husband is in marketing, "He does marketing." Plural form of doe. Third-person singular simple present indicative form of do.
“Do” is a verb in English that means “to carry out an action” and is used with the pronouns -I, -you, -we, -they, -these and -those. “Does” is the same verb but used only with third-person singular subject pronouns -he, -she, -it, -this, -that or -John.
1 : something that stands for something else : emblem The eagle is a symbol of the United States. 2 : a letter, character, or sign used instead of a word to represent a quantity, position, relationship, direction, or something to be done The sign + is the symbol for addition. symbol.
A std::string's allocation is not guaranteed to be contiguous under the C++98/03 standard, but C++11 forces it to be. In practice, neither I nor Herb Sutter know of an implementation that does not use contiguous storage.
Notice that the &s[0]
thing is always guaranteed to work by the C++11 standard, even in the 0-length string case. It would not be guaranteed if you did str.begin()
or &*str.begin()
, but for &s[0]
the standard defines operator[]
as:
Returns:
*(begin() + pos)
ifpos < size()
, otherwise a reference to an object of typeT
with valuecharT()
; the referenced value shall not be modified
Continuing on, data()
is defined as:
Returns: A pointer
p
such thatp + i == &operator[](i)
for eachi
in[0,size()]
.
(notice the square brackets at both ends of the range)
Notice: pre-standardization C++0x did not guarantee &s[0]
to work with zero-length strings (actually, it was explicitly undefined behavior), and an older revision of this answer explained this; this has been fixed in later standard drafts, so the answer has been updated accordingly.
Technically, no, since std::string
is not required to store its contents contiguously in memory.
However, in almost all implementations (every implementation of which I am aware), the contents are stored contiguously and this would "work."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With