Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is writing to &str[0] buffer (of a std:string) well-defined behaviour in C++11?

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?

like image 377
cubuspl42 Avatar asked Aug 06 '14 20:08

cubuspl42


People also ask

Is it correct to say writing to?

The practice in British English is to use write to when there is no direct object, so we would say I wrote to your uncle, rather than I wrote your uncle. However, when a direct object is present and it occurs after the name of the person addressed, to is omitted, so we would say I wrote your uncle a letter.

Is it writing to you or writing you?

The letter is a formal business letter, so it must be "I am writing to you". "Writing you" is colloquial and informal.

Can you say I am writing to you in an email?

It can be seen as a little old-fashioned, but more accurate would be to say it is formal to use "I am writing to". However, it is still common for business letters. It definitely gives a sense that the author and recipient do not have a close relationship.

When writing a letter is it to or for?

One writes a letter to someone. Having been written, the letter is a letter for that person. So the mail carrier would be at the door with a letter to Jason only if s/he had written said letter. To take another example: The person who used to live in my apartment has moved to a different apartment down the hall.


1 Answers

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) if pos < size(). Otherwise, returns a reference to an object of type charT with value charT(), where modifying the object leads to undefined behavior.

Your example satisfies the requirements stated above, so the behavior is well defined.

like image 99
Praetorian Avatar answered Sep 20 '22 21:09

Praetorian