访问 std::string 中的连续字符
在 C 中可能会遇到以下代码:
std::string s; s.resize(strLength); memcpy(&s[0], str, strLength); // Is this safe?
虽然在 std::vector 中使用 &s[0] 是安全的,但在 std::string 中使用它会引起担忧。本文检查了所提供代码的安全性。
在 C 98/03 中,不保证 std::string 的分配是连续的。然而,C 11 要求连续性。实际上,所有已知的实现都使用连续存储。
此外,C 11 标准保证 &s[0] 的安全,即使对于空字符串也是如此。这是因为 std::string 的 operator[] 定义为:
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
此外,data() 定义为:
Returns: A pointer p such that p + i == &operator[](i) for each i in [0, size()].
因此, &s[0] 提供指向字符串首字符的有效指针。
注意: 在标准化之前,访问&s[0] 对于空字符串是未定义的行为。不过,这个问题已在后来的标准草案中得到解决。
以上是在 C 中使用 `&s[0]` 访问 std::string 中的连续字符安全吗?的详细内容。更多信息请关注PHP中文网其他相关文章!