是否& s [0]指向std :: string中的连续字符? [英] Does "&s[0]" point to contiguous characters in a std::string?
问题描述
我正在进行一些维护工作,并且遇到以下情况:
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 );
我知道使用& s [0]是安全的,如果它是一个std :: vector,但是这是一个安全使用std :: string?
I know using &s[0] would be safe if it was a std::vector, but is this a safe use of std::string?
推荐答案
std :: string的分配不保证是连续的C ++ 98/03标准,但C ++ 11强制它。实际上,我和 Herb Sutter 知道不使用连续存储的实现。
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.
请注意,& s [0]
总是保证通过C ++ 11标准工作,即使在0长度字符串的情况下。如果您 str.begin()
或& * str.begin()
,但不能保证& s [0]
标准定义 operator []
为:
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:
返回:
*(begin()+ pos)
ifpos < size()
,否则引用T
,值为charT()
;参考值不应修改
Returns:
*(begin() + pos)
ifpos < size()
, otherwise a reference to an object of typeT
with valuecharT()
; the referenced value shall not be modified
继续, data()
定义为:
返回:指针
p
使中的每个
。i
的p + i ==& operator [](i)
> [0,size()]
Returns: A pointer
p
such thatp + i == &operator[](i)
for eachi
in[0,size()]
.
(注意范围两端的方括号)
(notice the square brackets at both ends of the range)
注意:预标准化C ++ 0x不能保证& s [0]
使用零长度字符串(实际上,它是明确未定义的行为),而这个答案的旧版本解释了这一点;这在以后的标准草案中已经解决,因此答案已相应更新。
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.
这篇关于是否& s [0]指向std :: string中的连续字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!