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(); }
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.
new
delete
data
std::string
MyObject
, , data , , char* 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.
std::uninitialized_fill
data - (, , , , ), .
new delete[] ( []). , MyObject , MyObject , .
delete[]
[]
.
throw
2 - RAII, .
, ,
1 ( , ).
:
MyObject() { string data( 200, '\0' ); if(something_is_wrong) throw exception(); }
new'ing, , , std::unique_ptr.
std::unique_ptr
, , std::terminate - ( ).
std::terminate
, , .
, - .
Source: https://habr.com/ru/post/1544343/More articles:Python groupby doesn't work as expected - pythonCMake + Jenkins to cover code with an unchecked file - code-coverageSpring -security remember me not working - spring-securityCount the appearance of each element in a large data stream - c ++Is there a way to print a formatted string from a log action in a CDT eclipse breakpoint action? - cException thrown in the constructor: is the destructor called? - c ++cx_freeze with docx package - pythonpython is not recognized in Windows CMD even after being added to PATH - pythonIs there a way to prevent the kendo datepicker popup from appearing when I click on a known container that is outside the datepicker? - javascriptPython 2to3 tool adds vowel to my whole - pythonAll Articles