我正在与旧的 C 风格界面作斗争。我有一个带有这样签名的函数:
/// if return_value == NULL only the length is returned
void f( char * return_value, size_t * size_only_known_at_runtime);
我的问题是,下面的代码安全吗?
std::size required;
f( NULL, &required );
std::string s;
s.resize(required);
f( &s[0], &required );
有没有更好的方法将数据放入字符串中?
最佳答案
是的,它是安全的,至少在 C++11 中是这样。来自 [string.require],强调我的:
The char-like objects in a
basic_string
object shall be stored contiguously. That is, for any basic_string object s, the identity&*(s.begin() + n) == &*s.begin() + n
shall hold for all values ofn
such that0 <= n < s.size()
.
这是 DR 530 的决议.在 C++11 之前,这在标准中并不明确,尽管它在实践中已经完成。
在 C++14 中,此要求已移至 [basic.string]:
A
basic_string
is a contiguous container (23.2.1).
其中 [container.requirements.general]:
A contiguous container is a container that supports random access iterators (24.2.7) and whose member types
iterator
andconst_iterator
are contiguous iterators (24.2.1).
其中 [iterator.requirements.general]:
Iterators that further satisfy the requirement that, for integral values
n
and dereferenceable iterator valuesa
and(a + n)
,*(a + n)
is equivalent to*(addressof(*a) + n)
, are called contiguous iterators.
关于c++ - 对 std::string 使用 operator [] 是否安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30187915/