Friday 15 August 2014

c++ - Using a delegating constructor to avoid leaks -



c++ - Using a delegating constructor to avoid leaks -

in talk next code has been shown unsafe because if constructor throws, destructor not called , leak resources:

class tworesources { tworesources(int x, int y) : m_a(nullptr), m_b(nullptr) { m_a = new a(x); m_b = new b(y); } ~tworesources() { delete m_b; delete m_a; } * m_a; b * m_b; };

a suggestion solution utilize delegating constructor, so:

class tworesources { tworesources() : m_a(nullptr), m_b(nullptr) { } tworesources(int x, int y) : tworesources() { m_a = new a(x); m_b = new b(y); } ~tworesources() { delete m_b; delete m_a; } * m_a; b * m_b; };

this safe because of:

c++11 15.2 [except.ctor]/2: "if non-delegating constructor object has completed execution , delegating constructor object exists exception, object's destructor invoked."

however in same slide, says:

just because can take advantage of rule doesn't mean should!

if code guaranteed safe, potential issues it?

just because safe doesn't mean doing idea.

for instance, using delegating constructor phone call crucial exception safety, that's far clear casual reader of code not familiar intricacies of language. month later, else looking @ code might think "why setting null if setting in constructor body again?" , remove it. ouch.

moreover, when managing lifetime manually, you'll need write own copy/move constructors/assignment operators. miss 1 , havoc results. if utilize unique_ptr manage lifetime, compiler-generated move constructor/assignment operator , destructor right thing, , complain if effort re-create without implementing re-create constructor yourself.

c++ c++11 memory-leaks

No comments:

Post a Comment