Re: [PATCH kvm-unit-tests 2/4] Introduce a C++ wrapper for the kvm APIs

Anthony Liguori
2010-11-24T17:28:14Z

On 11/24/2010 11:17 AM, Jes Sorensen wrote:
> On 11/24/10 18:11, Avi Kivity wrote:
>
>> On 11/24/2010 07:06 PM, Jes Sorensen wrote:
>>
>>> Sorry but that is utterly and completely bogus! The enforcement is only
>>> as good as the developers and maintainers make it,
>>>
>> class File {
>> public:
>> virtual ~File() {}
>> virtual void read(...) = 0;
>> virtual void write(...) = 0;
>> };
>>
>> Anyone wishing to implement this interface is forced to implement read
>> and write methods (callbacks) with exactly the right signature. The
>> compiler will complain if they don't. So if File is a good interface,
>> we can make the compiler force people to use it correctly.
>>
>> We can emulate this in C with ->ops-> things, but that's just
>> boilerplate and more places for people to get things wrong, or lazy and
>> take shortcuts.
>>
> In the mean time we spend our time debugging the runtime because the
> virtual functions don't behave as expected. In C we know what is going
> on, in C++ it is pray and hope.
>

The alternative in C is:

struct file_operations {
void (*release)(void);
void (*read)(...);
void (*write)(...);
};

struct file {
struct file_operations *ops;
};

If I do:

static file_operations posix_file_ops = {
.read = posix_file_read,
.write = posix_file_write,
};

struct posix_file {
struct file parent;
int fd;
};

void posix_file_init(struct posix_file *obj)
{
obj->parent.ops = posix_file_ops;
obj->fd = ...;
};

The compiler won't generate an error. Only upon a call to
file_release() will a null pointer dereference happens whereas in C++,
because this paradigm is structured in the language, the compiler can
help assist you.

Regards,

Anthony Liguori

> Jes
>