【发布时间】:2014-08-06 20:48:18
【问题描述】:
char hello[] = "hello world";
std::string str;
str.resize(sizeof(hello)-1);
memcpy(&str[0], hello, sizeof(hello)-1);
此代码在 C++98 中是未定义的行为。在 C++11 中是否合法?
【问题讨论】:
-
std::string缓冲区的新保证是连续的。但我不知道标准是否允许 writing 到该缓冲区,因为据我所知std::string的 COW 实现仍然是可能的。 -
你到底为什么要这样做?
-
@user3791372 有很多好的理由。示例:
string str; str.resize(8); fread(&str[0], 1, str.size(), file); -
C++11 中不允许使用 COW。看到这个答案stackoverflow.com/questions/12199710/…
-
所以在我看来,您的代码没有理由成为未定义的行为。
标签: c++ string c++11 buffer language-lawyer