默认构造的std :: string c_str()值
std::string s1;
std::string s2;
assert(strlen(s1.c_str()) == 0);
assert(s1.c_str() == s2.c_str());
这两个断言总是正确的吗?
我使用C ++ 11,并且已经检查了标准,§21.4.2中的表63说:
data()一个可复制的非挂钩指针,可以将0添加到它
size()0
容量()未指定的值
我认为 c_str()
与 data()相同
。但是我对这种定义有一些疑问。
-
“ 可以添加0个“ ==” 必须并且始终添加了0?
-
所有默认构造的std :: String是否共享相同的底层缓冲区?
我在GCC上测试,这两个断言是正确的。我想知道所有编译器总是正确的吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一断言可以成功。
c_str()
始终将指针返回到null端接的字符串,该字符串与std :: String :: String
对象相同的字符串内容,这是两个<<代码> S1
。不能保证第二个断言能成功。如果内容相同,则没有什么需要
c_str()
从std :: string
返回的。默认结构的字符串不需要共享相同的基础缓冲区。那将是特定标准库实施的实施细节。 (我认为libstdc ++会根据配置做出一些反兼容(?)原因(?)的原因,如果我记得正确,请参见- 启用 - dynamic-string
configure
option)。请注意,在C ++ 11之前,
data()
did 不是的效果与c_str()
。data()
不能保证给指向零端的字符串的指针。如果字符串是空的,则不允许将其返回的指针被删除。因此,用c_str()
用data()
在您的示例中,在C ++ 11之前,会导致对strlen 。
措辞“ and可以将0添加到它”有些怪异,我不确定它应该传达什么,但是对于C ++ 11(草稿N3337)
data()
的返回值在这样,data() + i ==&amp; operator [](i)
在范围内 in范围[0, size()]
和operator []
在 [strings.access]/2 返回Chart()
(aka a aka a null cartem)的参考)没有任何条件。奇怪的措辞也已通过2018年的社论更改替换,请参见 https://github.com/ cplusplus/draft/pult/1879 。
The first assertion is guaranteed to succeed.
c_str()
always returns a pointer to a null-terminated string with the same string contents as held by thestd::string
object, which is an empty string for boths1
.The second assertion is not guaranteed to succeed. There is nothing requiring the
c_str()
returned from astd::string
to be the same if the content is the same. Default-constructed strings do not need to share the same underlying buffer. That would be an implementation detail of a particular standard library implementation. (I think libstdc++ does something like this depending on configuration for some backwards-compatibility(?) reasons if I remember correctly, see the--enable-fully-dynamic-string
configure
option).Note that prior to C++11,
data()
did not have the same effect asc_str()
.data()
was not guaranteed to give a pointer to a null-terminated string. If the string was empty, then the pointer returned by it was not allowed to be dereferenced. So replacingc_str()
withdata()
in your examples would, prior to C++11, result in undefined behavior on the call tostrlen
.The wording "and can have 0 added to it" is somewhat weird and I am not completely sure what it is supposed to convey, but for C++11 (draft N3337)
data()
's return value is further specified in [string.accessors]/1 so thatdata() + i == &operator[](i)
for alli
in the range[0,size()]
andoperator[]
is specified in [strings.access]/2 to return a reference to aCharT()
(aka a null character) foroperator[](size())
without any conditions.The strange wording has also been replaced via editorial change in 2018, see https://github.com/cplusplus/draft/pull/1879.