I have dynamic memory allocation in my constructor and deallocation in
my destructor.
However if there is exception being thrown in constructor, the
destructor does not get called and memory leaks ensue.
What are some solutions to this problem (besides using auto_ptr).
To answer your question we need to know what you are allocating and
why.
The best scenario is not to use heap allocations directly in the first
place. However, that depends of a bunch of factors (ie: is the type
stored copyable and assigneable).
You can use templates to inject a constant std::size_t and common
containers to store a dynamic dataset. A silly templated class can
then store anything and, depending on the container type chosen, that
dataset can be stored in a variety of different arrangements (ie:
stored in contiguous space, sequenced on insertion, etc).
Its much, much simpler than allocating yourself and a lot less work, a
breeze to maintain, yet extremely resilient and easy to use.
#include <iostream>
#include <deque>
template< typename T, const std::size_t Size >
class Storage
{
std::deque<T> m_v;
public:
Storage() : m_v(Size) { }
Storage(const T& t_) : m_v(Size, t_) { }
// accessors
T& at(const std::size_t index)
{
return m_v.at(index);
}
void push_back(const T& t)
{
m_v.push_back(t);
}
};
int main()
{
try
{
Storage< int, 10 > integers;
std::cout << integers.at(9) << std::endl;
Storage< double, 10 > doubles(1.1);
std::cout << doubles.at(9) << std::endl;
Storage< char, 10 > chars('b');
std::cout << chars.at(9) << std::endl;
chars.push_back('c');
std::cout << chars.at(10) << std::endl;
// std::cout << another.at(11) << std::endl; // oops
}
catch(const std::exception& e)
{
std::cout << "Error: ";
std::cout << e.what() << std::endl;
}
}
/*
0
1.1
b
c
// Error: deque::_M_range_check // oops
*/