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

cub*_*l42 28 c++ string buffer language-lawyer c++11

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

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

Pra*_*ian 27

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

来自N3337,§21.4.5[string.access]

 const_reference operator[](size_type pos) const;
 reference operator[](size_type pos);
Run Code Online (Sandbox Code Playgroud)

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

您的示例满足上述要求,因此行为定义明确.