lurscher
lurscher

Reputation: 26943

strategy to free memory from std container in case of bad_alloc exception

i'm thinking in implementing the following strategy:

When handling a std::bad_alloc exception in a class method, memory will be attempted to be free whenever possible/meaningful before rethrowing the exception. So if an object has some std containers (std::vector<>) that can be freed, then we might do something like:

catch( std::bad_alloc& e ) {
  //free any memory in my std::vector member, how? by doing this dirty hack
  ~myVec();
  new ( &myVec) std::vector<myType>();
  throw; //rethrow exception
} 

Question: is the above "dirty hack" a safe strategy to deallocate memory on the way while a exception is being unrolled? what are the pros and cons?

Upvotes: 0

Views: 219

Answers (1)

Puppy
Puppy

Reputation: 146910

There's no need for you to do any such- the vector will be destructed automatically. That's how RAII works. Even if you wish to clear the vector in some other situation, it comes with a clear() method. Or you can just do vec = std::vector<T>();.

Upvotes: 3

Related Questions