gpt4 book ai didi

c++ - 字符串超出范围异常

转载 作者:行者123 更新时间:2023-11-28 00:13:58 26 4
gpt4 key购买 nike

我试图理解字符串中的 out_of_range 异常

#include<iostream>
#include<exception>
using namespace std;

int main()
{
try{
string str = "Hello";
str.at(100);//throws exception and get caught
//str[100]; //this is a run time error, program crashes
}
catch (out_of_range &e)
{
cout << e.what() << endl;
}

}

为什么数组访问字符串不会抛出任何异常和崩溃,而 .at 工作正常?

开发环境:VS2013

最佳答案

这是因为 [] 运算符不检查任何内容,而 at() 会检查任何内容。 CppReference 说:

std::basic_string::at

Returns a reference to the character at specified location pos. Bounds checking is performed, exception of type std::out_of_range will be thrown on invalid access.

std::basic_string::operator[]

Returns a reference to the character at specified location pos. No bounds checking is performed.

关于c++ - 字符串超出范围异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31522356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com