简体   繁体   中英

if map.insert fails how check its failure without using bad_alloc

If inside my code i am having a

class A;
A ob;
pair<map<int,A>::iterator,bool> ret;
ret=map.insert(pair<int,A>(1,ob));

If map fails to insert the ob because of out of memory, it will throw bad_alloc but is there any other way to check whether insert failed or not because i have a restriction to not use namespace and exception handling. Can't we use some kind of NULL pointer comparision statement?

The standard library reports failure to allocate memory by throwing std::bad_alloc . And while you are able to get around that with new(nothrow) , you can't do that with standard library classes.

Exception handling is part of C++; it is not an optional part of C++. Exceptions are the standard C++ way of handling erroneous conditions. I understand that you're working in an environment that doesn't allow you to catch exceptions, but you then have to accept that you're working in an environment that doesn't allow you to use all of C++. So there will be limitations on what you can do.

It should be noted that, unless you're using a custom allocator, it's unlikely that recovering from an "unable to allocate" error would be something easy to implement. Being unable to allocate memory would only happen because your application ran out of memory. In that case, just let the exception be thrown; since you don't use exceptions, it will escape main and cause your program to crash. Which is exactly what you want to happen.

If you do have some way to survive running out of allocatable address space, there's not much you can do if you can't catch exceptions. C++ standard library classes are designed to work with C++, and that means all of it. Including exceptions.

You're not allowed to use exception handling? Reconsider this. Parts of the C++ standard library use exceptions internally - this means you can't turn off exceptions using a compiler switch. If exceptions are enabled, you might as well use them - or of course you can implement your own exception-free standard library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM