Constructor leak

Do I have a leak if I allocate memory new in the constructor of the object and immediately after I throw an exception?

An object should not be constructed at all and, therefore, no destructor will be called, but what about this memory?

eg.

MyObject() {
  data = new char[200]; // Will this be leaked?

  if(something_is_wrong)
    throw exception();

}
+4
source share
4 answers

He will leak. Once you got a pointer from new, it should be deleted. The solution is to make a datasmart pointer (or in this case, probably a std::string); while the MyObjectdestructor will not be called, data element destructors are called.

+4
source

, , data , , char* data. :

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) {}
};

. , , . , std::uninitialized_fill.

+2

data - (, , , , ), .

new delete[] ( []). , MyObject , MyObject , .

.

  • throw.
  • data ( ).

2 - RAII, .

+1

, ,

MyObject() {
  data = new char[200]; // Will this be leaked?

  if(something_is_wrong)
    throw exception();

}

1 ( , ).

:

MyObject()
{
  string data( 200, '\0' );
  if(something_is_wrong)
    throw exception();
}

new'ing, , , std::unique_ptr.

, , std::terminate - ( ).


, , .

.

, - .


1) Under reasonable assumptions that you are not using a smart pointer to guarantee cleanup and ask this question without mentioning a smart pointer.
+1
source

Source: https://habr.com/ru/post/1544343/


All Articles