c++ - 对 std::string 使用 operator [] 是否安全

标签 c++ language-lawyer

我正在与旧的 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 of n such that 0 <= 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 and const_iterator are contiguous iterators (24.2.1).

其中 [iterator.requirements.general]:

Iterators that further satisfy the requirement that, for integral values n and dereferenceable iterator values a 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/

相关文章:

c - 函数显式前向声明后的准标准 C 函数头语法

c++ - 调用函数使我的代码慢得离谱

c++ - nim 游戏 : Issues with loops and program in general

c - 数组订阅是否算作获取对象的地址?

c++ - 在 C 和 C++ 中返回 void 类型

c - 中断对上下文的干扰有多大?如何恢复它?

c++ - 带有 std::error_code 的错误堆栈

C++ 帮助学生的指针

c++ - 使用 g++ 编译器构建 PJSIP

c++ - 如果特化已经被隐式实例化,它是否被隐式实例化?