Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaking in constructor

Tags:

c++

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();

}
like image 416
user129506 Avatar asked Feb 13 '23 18:02

user129506


2 Answers

It will leak. Once you have gotten a pointer from new it eventually needs to be deleted. 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.

like image 120
Simple Avatar answered Feb 15 '23 10:02

Simple


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.

like image 20
4pie0 Avatar answered Feb 15 '23 11:02

4pie0