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(使用前将#替换为@)