是否在C ++ 11中写入& str [0]缓冲区(std:string)良好定义的行为? [英] Is writing to &str[0] buffer (of a std:string) well-defined behaviour in C++11?

查看:93
本文介绍了是否在C ++ 11中写入& str [0]缓冲区(std:string)良好定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

This code is undefined behaviour in C++98. Is it legal in C++11?

推荐答案

是的,代码在C ++ 11中是合法的, code> std :: string 保证是连续的,你的代码避免覆盖终止的NULL字符(或初始化值 CharT )。

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).

从N3337起,§21.4.5[string.access]

From N3337, §21.4.5 [string.access]


 const_reference operator[](size_type pos) const;
 reference operator[](size_type pos);

1需要: pos< = size ()

2返回: *(begin()+ pos) if pos< size()。否则,返回对 charT 的值为 charT()的对象的引用,其中修改对象导致未定义行为。

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.

这篇关于是否在C ++ 11中写入&amp; str [0]缓冲区(std:string)良好定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆