How can I stick to RAII?

M

Michael Tsang

In C++, everything should be acquired and initialised in constructors and
released in destructors but I'm in a trouble trying to do this. Nearly all
code written by me requires interacting with C libraries, most commonly
POSIX so I am forced to scatter my code with open(), close(), opendir(),
closedir(), fdopen(), pipe(), mmap(), etc inside middle of functions and it
is very difficult to get it right when the code throws exceptions. I know
that RAII is the only way to prevent leaking non-memory resources such as
file handles.
 
M

Michael Tsang

Leigh said:
Interacting with C libraries shouldn't be an issue when using RAII, e.g.

class foo
{
private:
struct handle
{
handle() { }
~handle() { close(...); }
};
public:
foo(...) : iHandle(open(...)) {}
private:
handle iHandle;
};

/Leigh

How about when using calls such as dup2(), pipe(), fdopen(), etc?
 
J

Jorgen Grahn

But the OP query relates to interacting with libc functions like
open(), fopen(), popen(), pipe(), etc. ScopeGuards are pretty close
to ideal to make it easy to write exception safe C++ code that
interact with lower level C libraries.

But if you're wrapping a C library, I guess you can often find some
abstraction level where it makes sense to introduce a class, and then
you use such objects instead of thinly wrapped (in this case) file
descriptors. I assume that's what Leigh meant.

For example, I think it's generally better to wrap pipe() in some way
suited to your specific application, rather than to just fix the
possible resource leak.

/Jorgen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top