Thursday, April 23, 2015

C++11 bailout trickery

Is someone C++11 guru enough to make a statement whether
the following C++11 code is correct? In particular on
whats happening on line 24, as the lambda should not
harvest the memory structures (scope?).
To me, everything looks OK. If thats the case, it would ease
a lot of cleanup routines on error returns from functions.
Please leave a comment.

Sample C++ code


2 comments:

Jaak Ristioja said...

Your example leaks when an allocation throws std::bad_alloc when you run out of memory. There are better scope exit techniques which rely on destructors being called when control flow exists the scope. These get called implicitly (without the need for out(cleanups);) even during stack unwinding during exception handling.

For the arrays s you could instead use:

unique_ptr s[1000];

Instead of using ::open and C-style file descriptors, use some file class which closes the file on scope exit, e.g.

std::fstream file{"/etc/passwd", ios_base::in};

Unknown said...

Your code should work just fine. The lambda is not evaluated at line 24, which you should be able to verify by supplying a custom class with a destructor instead of a POD type.