Apache resigns from the Java Community Process executive committee
Posted Dec 15, 2010 1:41 UTC (Wed) by
HelloWorld (guest, #56129)
In reply to:
Apache resigns from the Java Community Process executive committee by cmccabe
Parent article:
Apache resigns from the Java Community Process executive committee
It's possible to write correct code in C++, but it requires a *lot* of self-discipline. You can make all the same mistakes a C programmer can, plus a whole lot more.
I believe that this argument is a red herring for two reasons. The first is that it doesn't take into account how likely you are to make a certain typical C mistake in C++. For example, it's very easy to make a mess of dynamically allocated arrays in C, and while this is also possible in C++, you're much more unlikely to, as you'd probably just use a container class. The second is that if you do the C equivalent of the things that may cause bugs in a C++ program, you're at least as (and probably more) likely to make the same mistake. Your example would look something like this in C:
#include <string.h>
#include <stdlib.h>
struct Foo_vtbl {
void (*destroy)();
};
struct Foo {
struct Foo_vtbl *vtbl;
};
void destroy_Foo(struct Foo *f) {
}
struct Foo_vtbl Foo_vtbl = { &destroy_Foo };
void delete_Foo(struct Foo *f) {
f->vtbl->destroy(f);
free(f);
}
void construct_Foo(struct Foo *f) {
f->vtbl = &Foo_vtbl;
}
struct Foo *new_Foo() {
struct Foo *f = malloc(sizeof(struct Foo));
construct_Foo(f);
return f;
}
struct Bar_vtbl {
struct Foo_vtbl foo_vtbl;
};
struct Bar {
struct Foo foo;
char *str;
};
void destroy_Bar(struct Bar *b) {
free(b->str);
b->foo.vtbl = &Foo_vtbl;
destroy_Foo(&b->foo);
}
struct Bar_vtbl Bar_vtbl = { { &destroy_Bar} };
void delete_Bar(struct Bar *b) {
b->foo.vtbl->destroy(b);
free(b);
}
void construct_Bar(struct Bar *b) {
construct_Foo((struct Foo *)b);
b->foo.vtbl = (struct Foo_vtbl*) &Bar_vtbl;
b->str = malloc(6);
strcpy(b->str, "Hello");
}
struct Bar *new_Bar() {
struct Bar *b = malloc(sizeof(struct Bar));
construct_Bar(b);
return b;
}
int main(void) {
struct Foo *f = (struct Foo *)new_Bar();
delete_Foo(f);
}
This is the kind of crap you need to write in order to do trivial object-oriented stuff in C. Note that making a destructor non-virtual is just as easy as in C++, just change
f->vtbl->destroy(f);
to
destroy_Foo(f);
in delete_Foo - it's still perfectly innocent-looking! And there are dozens of other opportunities for making silly mistakes in the above code that aren't there in the C++ version. So, while C++ certainly has its problems, I'd choose it over C any day of the week.
(
Log in to post comments)