LWN.net Logo

Open-before-use

Open-before-use

Posted Apr 1, 2008 10:56 UTC (Tue) by epa (subscriber, #39769)
Parent article: How Do I Make This Hard to Misuse?

It's hard for the compiler to ensure that the user calls your "open" routine before your other routines, but an "assert()" can at least get you to this level.
In C++ it would be normal practice to make the 'open' routine the constructor, so you automatically have to call it first before any member functions. But you can do this in C too, if your functions all take a handle argument and open() is the only one that generates such a handle.


(Log in to post comments)

Open-before-use

Posted Apr 1, 2008 12:59 UTC (Tue) by nlucas (subscriber, #33793) [Link]

But you can't do it in practice many times, because it's normal to need to "reopen" the
resource (because of a connection error, the usb device was disconnected, you don't know the
resource name beforehand, etc.), which means the added logic for this case is just the same as
not opening it in the constructor (the default constructor, at least) and providing
"open"/"Close" methods.

Open-before-use

Posted Apr 1, 2008 15:35 UTC (Tue) by NAR (subscriber, #1313) [Link]

That still wouldn't solve the problem, one could write code like this, even if only an "open" would return a valid handle:
handle_t* handle;
read(handle);

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds