19

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?

ayane_m
  • 962
  • 2
  • 10
  • 26
  • 3
    Did you try a reference for each? There is a difference, which should be pretty easy to spot when comparing references. – chris Feb 05 '13 at 02:13
  • 2
    Wait, you decided to switch from `.at()` to `operator[]` *before* looking into a book or online reference ? – us2012 Feb 05 '13 at 02:15
  • well, I read operator[] was faster, but didn't know why... – ayane_m Feb 05 '13 at 16:57

3 Answers3

35

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.

Community
  • 1
  • 1
Jack
  • 131,802
  • 30
  • 241
  • 343
18

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.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
7

std::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.

string::operator[]

Returns a reference to the character at specified location pos. No bounds checking is performed. It's undefefined behavior to access out-of-boundary with operator[].

string::operator[] should be silghtly faster than std::string::at

see the reference

billz
  • 44,644
  • 9
  • 83
  • 100