15

私は学校で教えられstring::atましたが、文字列ライブラリを探索することでstring::operator[]、これまでに見たことのない を見つけました。

今使っていて、それ以来使っoperator[]ていませんatが、違いは何ですか?サンプルコードは次のとおりです。

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

出力に関しては基本的に同じですが、私が気づいていない微妙な違いはありますか?

4

3 に答える 3

30

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.

于 2013-02-05T02:16:15.213 に答える
17

at does bounds checking, exception of type std::out_of_range will be thrown on invalid access.

operator[] does NOT check bounds and thus can be dangerous if you try to access beyond the bounds of the string. It is a little faster than at though.

于 2013-02-05T02:16:16.727 に答える
6

std::string::at

指定された位置 pos にある文字への参照を返します。境界チェックが実行され、タイプ std::out_of_range の例外が無効なアクセスでスローされます。

文字列::演算子[]

指定された位置 pos にある文字への参照を返します。境界チェックは実行されません。で境界外にアクセスするのは未定義の動作operator[]です。

string::operator[]よりわずかに速いはずですstd::string::at

参照を参照してください

于 2013-02-05T02:16:36.923 に答える