写入 &str[0] 缓冲区(std:string)在 C++11 中是明确定义的行为吗?

2024-02-06

char hello[] = "hello world";
std::string str;
str.resize(sizeof(hello)-1);
memcpy(&str[0], hello, sizeof(hello)-1);

此代码是 C++98 中未定义的行为。它在 C++11 中合法吗?


是的,该代码在 C++11 中是合法的,因为存储std::string保证是连续的,并且您的代码避免覆盖终止 NULL 字符(或初始化的值)CharT).

从 N3337 开始,§21.4.5 [字符串.访问]

 const_reference operator[](size_type pos) const;
 reference operator[](size_type pos);

1 要求: pos <= size().
2 退货: *(begin() + pos) if pos < size()。否则,返回对类型对象的引用charT有价值charT(),其中修改对象会导致未定义的行为。

您的示例满足上述要求,因此行为定义良好。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

写入 &str[0] 缓冲区(std:string)在 C++11 中是明确定义的行为吗? 的相关文章

随机推荐