Re: Best way to allocate memory in the constructor
In article <4791ca3c$0$10629$4fafbaef@reader2.news.tin.it>,
salvatore.benedetto@gmail.com says...
Hi,
What's the best way to allocate memory in the constructor and avoid
memory leaks if the constructor fails?
One common method is with a smart pointer that automatically frees the
memory when the pointer goes out of scope.
Let's say that in my constructor, I have to allocate memory
with malloc (i.e. an array of char *)several times, and one
of them fails.
Why would we say any such thing? There's _rarely_ a good reason to use
malloc in C++.
An array of char * is typically used to hold a string -- to do that,
you're far better off simply creating three instances of std::string,
and being done with it. If you're really using them as an array instead
of a string, consider something like an std::vector<char> instead.
If you really insist on rolling your own and using malloc, you could
write code something like this:
class malloc_char {
char *data;
public:
malloc_char(size_t size) {
data = malloc(size);
if (NULL == data)
throw bad_alloc("malloc failed");
}
~malloc_char() { free(data); }
};
class your_class {
malloc_char first, second, third;
public:
your_class(size_t size1, size_t size2, size_t size3)
: first(size1), second(size2), third(size3)
{}
};
In case of an exception during a ctor, any fully-constructed sub-objects
are destroyed automatically. That means if (for example) the malloc
fails in creating the third item, the destructors for first and second
are called automatically. Since the destructor calls free, the
associated memory is automatically freed.
You're generally going to be better off using vector or string though.
--
Later,
Jerry.
The universe is a figment of its own imagination.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]