No. The first (deleting entries) frees the entires back to the heap, the second (clearing the map) releases dangling references to the heap. Again, you need to do both.
looks both of ways are safe because when you insert a pair to a map, map will make a copy (or copy construct if any elment of pair is a C++ object ) of pair.
But, you MUST replace
1 2 3
delete o1;
o1 = NULL;
aMap.erase(1);
with
1 2 3 4 5 6
if (o1)
{
delete o1;
o1 = NULL;
}
aMap.erase(1);
because, your new operation may fail.
and you must make the whole operation atomic such as puts mutex around it if more than one thread can run this operation.
binaryboy is right. If this is a multi-threaded app, you must put a mutex around just about anything involving STL containers. Thread-safety in C++ is very implementation specific.
A more important point is that pointers are rather unsafe (hard to manage) in a threaded environment. Use copies or use a thread-safe shared pointer. Here's why: in a threaded environment, you have to make sure that no object is deleted while any thread has a pointer to that object. You need to protect each object with a lock to ensure the object the pointer points to is not deleted from under you. It doesn't matter which option you choose if another thread is using the pointer when the delete is called. Often a copy is cheaper than managing locks.
Mutex locks are in place already since our application runs in solaris multithreaded enironment.
NULL checks are also taken care, but if use the approach #1
i.e.,
approach #1
aMap.erase(1);
delete o1;
o1 = NULL;
its crashing at "delete o1" ... see the stack trace for the same