Do I leak if I allocate memory with new in the constructor of an object and immediately after I throw an exception?
The object shouldn't be constructed at all and thus no destructor will be called, but what about that memory?
e.g.
MyObject() {
data = new char[200]; // Will this be leaked?
if(something_is_wrong)
throw exception();
}
It will leak. Once you have gotten a pointer from new
it eventually needs to be delete
d. The solution is to make data
a smart pointer (or in this case, probably a std::string
); while MyObject
's destructor won't be called, data members' destructors are called.
Yes, it will be a leak unless data
is kind of handle, smart pointer and not a raw pointer char* data
. A safe variant of this is:
class MyObject {
std::vector<char> data; // or some handle/smart pointer (i.e. unique_ptr)
// it might be just std::string
public:
MyObject( int sz) : data( sz) {}
};
In this case the memory used is now managed by vector. You can of course do it by yourself what is actually done in vector already and is exception safe. This is you can use approach similar to std::uninitialized_fill
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With