LWN.net Logo

Object-oriented design patterns in the kernel, part 1

Object-oriented design patterns in the kernel, part 1

Posted Jun 2, 2011 13:48 UTC (Thu) by cesarb (subscriber, #6266)
In reply to: Object-oriented design patterns in the kernel, part 1 by foom
Parent article: Object-oriented design patterns in the kernel, part 1

I believe that, unless your class has only plain old data members (the kind you would find in a C struct), doing a bzero of *this has the potential of blowing up. The compiler can add extra hidden members (like the vtable pointer), and you would be overwriting them.

That is, I believe what you are doing is safe only if:

- All the integer and bitfield members (and only them) are in the parent class;
- The parent class is zeroing only itself (that is, it is doing the sizeof(*this) itself, instead of being passed that value by the child class);
- The parent class has no virtual member functions or anything else that could make the compiler add C++ magic to it.

That said, I am no language lawyer, and would not be surprised if several clauses scattered all over the standard combine to say that even then you are still doing something undefined.

Why not move all these variables into a plain C-style struct, add it to your object as a member, and zero it on the constructor? That way sounds much safer to me, and I doubt the C++ standard would break it (since breaking it would break compatibility with C).


(Log in to post comments)

Object-oriented design patterns in the kernel, part 1

Posted Jun 3, 2011 11:20 UTC (Fri) by liljencrantz (guest, #28458) [Link]

What makes you assume the parent is talking C++ and not C? Am I missing something or are you?

Object-oriented design patterns in the kernel, part 1

Posted Jun 3, 2011 13:51 UTC (Fri) by sethml (subscriber, #8471) [Link]

Presumably because *this means something special in C++, and is not a common thing to write in C.

I've written this bug in C++ (memset(this, 0, sizeof(*this))) - clobbering your vtable pointer is pretty annoying to debug. My horrible hacky fix was just to zero the data portion of the class: memset(&firstMember, 0, (char *)(&lastMember + 1) - (char *)&firstMember)

Object-oriented design patterns in the kernel, part 1

Posted Jun 4, 2011 10:11 UTC (Sat) by liljencrantz (guest, #28458) [Link]

I always use the name «this» for the object pointer when doing OOP in C. From what I've seen, this is a common convention.

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