Manual resource management is error-prone

The first and most obvious danger of managing every resource manually, with explicit calls to acquire and release each one, is that it is easy to forget the latter. For example see the following:

{    object_counter* p = new object_counter;      ... many more lines of code ... } // Were we supposed to do something here? Can't remember now...

We are now leaking a resource (object_counter objects, in this case). If we did this in a unit test, it would fail, as follows:

TEST(Memory, Leak1) {    object_counter::all_count = object_counter::count = 0;    object_counter* p = new object_counter;    EXPECT_EQ(1, object_counter::count);    EXPECT_EQ(1, object_counter::all_count);    //delete p;    // Forgot that EXPECT_EQ(0, object_counter::count); ...

Get Hands-On Design Patterns with C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.