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

后端 未结 3 1728
無奈伤痛
無奈伤痛 2020-12-07 01:01

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 u

相关标签:
3条回答
  • 2020-12-07 01:22

    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.

    0 讨论(0)
  • 2020-12-07 01:28

    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

    0 讨论(0)
  • 2020-12-07 01:44

    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.

    0 讨论(0)
提交回复
热议问题