char hello[] = "hello world";
std::string str;
str.resize(sizeof(hello)-1);
memcpy(&str[0], hello, sizeof(hello)-1);
This code is undefined behaviour in C++98. Is it legal in C++11?
Join Stack Overflow to learn, share knowledge, and build your career.
char hello[] = "hello world";
std::string str;
str.resize(sizeof(hello)-1);
memcpy(&str[0], hello, sizeof(hello)-1);
This code is undefined behaviour in C++98. Is it legal in C++11?
Yes, the code is legal in C++11 because the storage for std::string
is guaranteed to be contiguous and your code avoids overwriting the terminating NULL character (or value initialized CharT
).
From N3337, ยง21.4.5 [string.access]
const_reference operator[](size_type pos) const; reference operator[](size_type pos);
1 Requires:
pos <= size()
.
2 Returns:*(begin() + pos)
ifpos < size()
. Otherwise, returns a reference to an object of typecharT
with valuecharT()
, where modifying the object leads to undefined behavior.
Your example satisfies the requirements stated above, so the behavior is well defined.
char
that is a copy of the requested location provided that reads and writes of it (and it alone) are as expected?
– BCS
Oct 20 '14 at 13:36
data()
member function. Between the two, it'll be clear that a conforming implementation needs to have contiguous storage, and operator[]
returns a reference to an element within this storage.
– Praetorian
Oct 20 '14 at 14:32
std::string
buffer being contiguous. But I don't know if standard allows writing to that buffer, because as far as I know COW implementations ofstd::string
are still possible. – cubuspl42 Aug 6 '14 at 20:52string str; str.resize(8); fread(&str[0], 1, str.size(), file);
– cubuspl42 Aug 6 '14 at 21:00