How to check if map could be created, if I don't use exceptions?
I want to use map
in C++, but I don't use exceptions. After using map<int, int> my_map
in a function, how can I check if it managed to allocate memory internally (I understand that with exceptions any new insi开发者_运维问答de that can't allocate memory will throw an exception)?
Whether or not you use exceptions, the standard containers will (if they are using their default allocators) throw std::bad_alloc
if a memory allocation fails. If you don't catch this, then your program will terminate - so there is no way to check for success without catching the exception in this case.
If you really want to eradicate exceptions (which in my opinion is a bad idea, even if you don't want to use the Standard Library), then you will have ditch the standard containers, rewriting whatever containers you want to use a non-standard allocation model, and check for and propagate any failures. The standard containers all assume that allocation will either succeed or throw, so they cannot be used with an allocator that doesn't give that guarantee.
Whether or not you use exceptions, the C++ library uses them for allocation errors. If you really want to avoid them, you need to learn about allocators, or at least your own global operator new, and come up with some other scheme (calling a function in a global variable?) when memory is unavailable.
If you don't want exceptions to be thrown around, you should write your own allocator and use that in your map: typedef std::map<int, int, std::less<int>, MyAllocator> my_map;
.
You'll have to come up with your own internal logic for handling out-of-memory situations, though, and the standard interface doesn't provide any obvious interface.
As a hybrid solution, you could write an allocator that takes memory from a static memory pool and calls some global failure handler when that's full.
Well, exception disabled are not part of the C++ standard, so you'll be going into compiler-specific behavior. That being said, at least with GCC, the default operator new will, instead of throwing an exception if malloc() fails, simply abort the program if compiled with -fno-exceptions.
精彩评论