RE: [PATCH 00/45] C++: Convert the kernel to C++

David Laight
2024-01-11T19:41:24Z

From: Chris Down
> Sent: 11 January 2024 12:40
>
> H. Peter Anvin writes:
> >We already *do* use constructors and *especially* destructors for a
> >lot of objects, we just call them out.
> >
> >Note that modern C++ also has the ability to construct and destruct
> >objects in-place, so allocation and construction/destruction aren't
> >necessarily related.
> >
> >There is no reason you can't do static initialization where possible;
> >even constructors can be evaluated at compile time if they are
> >constexpr.

But the compiler often doesn't - look at the generated code and marvel
at all the constructors for static items.
Oh yes, and all the destructors that pretty much always get called
in the wrong order leading to SIGSEGV on exit().
C++ programs pretty much have close all files and use _exit().

> Side note for the constructor and destructor discussion: should we be more
> widely marketing the __cleanup() infrastructure that Peter added a year or so
> ago? It likely helps a lot with at least some of these cases. In systemd we use
> __attribute__((cleanup)) pretty widely and my experience is that it's made the
> code a lot easier to both create and consume.

And harder for us 'old fogies' to quickly read for correctness.

IIRC some bugs got committed during some 'simple applications'
because of the real hoops you have to go through to correctly
tidy up a malloc()ed buffer that might be passed on.

I've seen the same issue with some C++ code that was like:
(Pardon my C++ :-)
foo = new();
try {
add_foo_to_list(foo);
} except {
free(foo);
}
The problem is that you have no idea whether the exception was
thrown before or after 'foo' was saved.
Since pretty much everything can 'throw' you really can't tell.
OTOH if add_foo_to_list() returns an error code you can know
(and check) that zero is returned iff the pointer has been saved.

Then there is function and class member overloading.
How may times have you renamed a structure member (etc) and used
the compiler to find out where it is used?
I'm pretty sure that is hard work in C++.

And don't forget the default copy constructor...

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
Registration No: 1397386 (Wales)