string :: at和string :: operator []有什么区别?

aya*_*ane 10 c++ string

string::at在学校接受教育,但是通过探索我看到的字符串库string::operator[],我之前从未展示过.

我现在正在使用operator[]并且从未使用at过,但有什么区别?以下是一些示例代码:

std::string foo = "my redundant string has some text";
std::cout << foo[5];
std::cout << foo.at(5);
Run Code Online (Sandbox Code Playgroud)

它们在输出方面基本相同,但是有一些我不知道的细微差别吗?

Jac*_*ack 20

是的,有一个主要区别:使用.at()对传递的索引进行范围检查,如果它超过字符串的末尾则抛出异常,而在这种情况下operator[]只会带来未定义的行为.


Kar*_*k T 12

at 进行边界检查,std::out_of_range无效访问时会抛出类型异常.

operator[] 不检查边界,因此如果您尝试访问超出字符串的边界可能会很危险.它比它快一点at.


bil*_*llz 5

std :: string :: at

返回对指定位置pos处字符的引用。执行边界检查,无效访问将引发类型为std :: out_of_range的异常。

字符串:: operator []

返回对指定位置pos处字符的引用。不执行边界检查。使用访问边界是不确定的行为operator[]

string::operator[] 应该比 std::string::at

参考