2
string p="a";
cout<<p[4];

This piece of code doesn't give any error. Does this mean the string data type in C++ is also not bounded as are the arrays?

CinCout
  • 9,486
  • 12
  • 49
  • 67

2 Answers2

6

Your code has undefined behavior.

std::string::operator[] does not perform any bound checks.

std::string::at() on the other hand performs bound checks and throws an exception of type std::out_of_range when you access data that is out of bounds.

Does this means the string "data type" in C++ is also not bounded as are the arrays?

Of course std::string has bounds. The way you access its contents is where the difference comes in whether bound checks will be performed or not.

CinCout
  • 9,486
  • 12
  • 49
  • 67
2

See std::string::at(), it will throw an std::out_of_range on error. The operator [] does not check bounds.

The same is true for standard containers, which provide random access (std::array, std::vector, std::deque, std::map, std::unordered_map): normally, in C++ you are supposed to always ensure no out-of-range access occurs. This allows for a greater performance of the program. But in some specific cases, it could be beneficial to use exception handling (via try and catch) instead, sacrificing some performance.

heap underrun
  • 1,846
  • 1
  • 18
  • 22
  • So does [] operator doesn't check bound for anything it is used in, like vectors, maps and sets in STL? – Ashish Chourasia Dec 19 '20 at 18:54
  • 4
    @AshishChourasia It's behavior depends on the container. For vectors it doesn't check anything, for maps it automatically inserts the element if it's missing, and it doesn't work on sets. Also, most compilers (more precisely, standard library implementations) have a way to turn on the bounds checks. – HolyBlackCat Dec 19 '20 at 18:59