Why is the bad_alloc exception not const?

Is there a special reason why the std::bad_alloc exception is not a constant?

from cplusplus:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
include <iostream>     // std::cout
#include <new>          // std::bad_alloc

int main () {
  try
  {
    int* myarray= new int[10000];
  }
  catch (std::bad_alloc& ba)
  {
    std::cerr << "bad_alloc caught: " << ba.what() << '\n';
  }
  return 0;
}


It just seems a little more logical to be const since no data really gets changed. Shouldn't every piece of data where nothing is changed be a const?
You can use const when you catch the exception if you want.

 
  catch (const std::bad_alloc& ba)
Last edited on
The type of the exception object is the static type of expression with top-level cv-qualifiers removed.
...
Unlike other temporary objects, the exception object is considered to be an lvalue argument when initializing the catch clause parameters, so it can be caught by lvalue reference, modified, and rethrown.
http://en.cppreference.com/w/cpp/language/throw
You can use const when you catch the exception if you want.


Doesn't that depend on the compiler though? When throwing char * vs const char *, I found that Visual Studio didn't distinguish the two but g++ did.
If you throw a char* it can be catched by both char* and const char*.
If you throw a const char* it can only be catched by a const char*.

Note that this has nothing to do with what we discussed earlier because const here means that what is being pointed to is read-only, not that the pointer itself is read-only. You can catch both a char* and a const char* by reference or const-reference if you want.

1
2
3
4
5
6
7
8
9
10
11
12
try
{
	throw "Exception!"; // throws a const char*
}
catch (char* const& exp) // catching the char* by const-reference
{
	std::cerr << "char* : " << exp << "\n";
}
catch (const char* const& exp) // catching the const char* by const-reference
{
	std::cerr << "const char* : " << exp << "\n";
}
Last edited on
Note that this has nothing to do with what we discussed earlier because const here means that what is being pointed to is read-only


Right. I see now. I was never catching const pointers or pointers, I was just catching pointers that were POINTING to consts or non-consts.

Which is different...

Good point.
Last edited on
Topic archived. No new replies allowed.