依靠空std :: string的索引0是否不好? [英] Is it bad to depend on index 0 of an empty std::string?

查看:91
本文介绍了依靠空std :: string的索引0是否不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::string my_string = "";
char test = my_string[0];

我注意到这不会崩溃,并且每次测试时,是0。

I've noticed that this doesn't crash, and every time I've tested it, test is 0.

我可以依靠它始终为0吗?还是随意?

Can I depend on it always being 0? or is it arbitrary?

这是不好的编程吗?

编辑:
从某些注释中,我收集到一些关于此用途的误解。

From some comments, I gather that there is some misunderstanding about the usefulness of this.

此操作的目的不是检查字符串是否为空。
不需要检查字符串是否为空。

The purpose of this is NOT to check to see if the string is empty. It is to not need to check whether the string is empty.

这种情况是有一个字符串可能为空,也可能不是空。
我只关心该字符串的第一个字符(如果它不是空的)。

The situation is that there is a string that may or may not be empty. I only care about the first character of this string (if it is not empty).

在我看来,检查到

if (! my_string.empty())
    test = my_string[0];
else
    test = 0;

相反,我只需查看第一个字符即可,而无需检查字符串是否为空

Instead, I can just look at the first character without needing to check to see if the string is empty.

test = my_string[0];


推荐答案

C ++ 14



否;您可以依靠它。

21.4.5.2 (或[string.access])中,我们可以找到:

In 21.4.5.2 (or [string.access]) we can find:


返回值: *(begin()+ pos)如果位置< size()。否则,返回对值为 charT()的类型为 charT 的对象的引用,其中修改该对象将导致未定义

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.

换句话说,当 pos == size()( (当两者均为0时为true),操作员将返回对默认构造的字符类型的引用,禁止您对其进行修改

In other words, when pos == size() (which is true when both are 0), the operator will return a reference to a default-constructed character type which you are forbidden to modify.

对于空(或0大小)字符串,它不是特殊情况,并且在每个长度上都相同。

It is not special-cased for the empty (or 0-sized) strings and works the same for every length.

最肯定的是 C ++ 98。

And most certainly C++98 as well.

这要视情况而定。

这里是 21.3.4.1

Here's 21.3.4.1 from the official ISO/IEC 14882:


返回:如果 pos< size(),返回 data()[pos] 。否则,如果 pos == size(),则const版本返回 charT()。否则,行为是不确定的。

Returns: If pos < size(), returns data()[pos]. Otherwise, if pos == size(), the const version returns charT(). Otherwise, the behavior is undefined.

这篇关于依靠空std :: string的索引0是否不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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