[cap-talk] Coding style in C++, isolating the bad parts with private constructors and friends?

Rob Meijer capibara at xs4all.nl
Tue Dec 15 23:21:59 PST 2009


On Tue, December 15, 2009 05:48, Ben Kloosterman wrote:
> Hi Rob ,
>
> I don't see how we are improving things for security as any class can
> inherit from FooCreator and do what it wants with Foo

Not so. FooCreator has a private constructor, so you can create a new
class that inherits from FooCreator, but you can not instantiate any
object from that class. To be sure I tried it, and the compiler states:

test.cpp: In constructor ‘MyCreator::MyCreator()’:
test.cpp:22: error: ‘FooCreator::FooCreator()’ is private
test.cpp:29: error: within this context

The combination of the private constructor and the friend declaration:

  friend int main(int argc,char **argv);

Limits the creation of the FooCreator to the program's main.
The same type of construct in the Foo class limits creation of a Foo object
to FooCreator objects. The result seems, that with the exception of things
that would exploit the memory unsafeness , if you have you established
that a system call only occurs in the code within the Foo class, you can
be sure that anything with authority to do the system call has to be
handed either a FooCreator object that was created in main, or a Foo
object that was created with this Foo creator.


For me the limitations seem to be posed mainly by C++ memory insecurity.

There however seem to be major advantages with respect to for example
code reviews. If you can reduce the number of code lines that count as
'trusted' code, you can increase the amount of eyeball to determine if
this code is 'trustworthy' code. That is, a program of 10.000 lines of
code that gets 40 man hours of code review indiscriminately will get 14
seconds of eyeball per line of trusted code. If we can reduce the amount
of trusted code to 1/10 of the code-base, we would get 140 seconds of
eyeball per line of code. This means by way of a focussed code review we
get a great
increase of the trustworthiness of our trusted code. While I feel the
memory insecurity of C++ greatly reduces the overall trustworthiness, this
basic rule still applies.

Rob



More information about the cap-talk mailing list