Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

c++ - What is the difference between string::at and string::operator[]?

I was taught string::at in school, but by exploring the string library I saw string::operator[], which I was never shown before.

I'm now using operator[] and haven't used at since, but what is the difference? Here is some sample code:

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

They are essentially the same in terms of output, but are there some subtle differences I'm not aware of?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, there is one major difference: using .at() does a range check on index passed and throws an exception if it's over the end of the string while operator[] just brings undefined behavior in that situation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...