What's the best practice to prevent memory leak if an exception thrown in constructor?

前端 未结 4 512
清酒与你
清酒与你 2021-02-08 02:55

I know if an exception is thrown in constructor, destructor will not be called(simple class, no inheritance). So if an exception is thrown in constructor and there is a chance s

4条回答
  •  盖世英雄少女心
    2021-02-08 03:40

    Avoid the need to allocate memory on the heap (via new and new[]) by using standard library containers. If this is not possible, always use a smart pointer, like std::unique_ptr<> to manage memory allocated on the heap. Then you will never need to write code for deleting the memory and it will be automatically cleaned up even in case an exception is thrown in your constructor (actually a constructor is often a likely place for an exception, but a destructor should really not throw).

提交回复
热议问题