为什么使用此POD结构作为基类是危险的? [英] Why can it be dangerous to use this POD struct as a base class?
问题描述
我和一个同事进行过这次对话,结果很有趣。假设我们有以下POD类
I had this conversation with a colleague, and it turned out to be interesting. Say we have the following POD class
struct A {
void clear() { memset(this, 0, sizeof(A)); }
int age;
char type;
};
清除
旨在清除所有成员,设置为 0
(逐字节)。如果我们使用 A
作为基类可能会出错?这里有一个微妙的错误来源。
clear
is intended to clear all members, setting to 0
(byte wise). What could go wrong if we use A
as a base class? There's a subtle source for bugs here.
推荐答案
编译器可能为A添加填充字节。 sizeof(A)
扩展到 char类型
(直到填充结束)。但是在继承的情况下,编译器可能不会添加填充字节。因此,调用 memset
将覆盖部分子类。
The compiler is likely to add padding bytes to A. So sizeof(A)
extends beyond char type
(until the end of the padding). However in case of inheritance the compiler might not add the padded bytes. So the call to memset
will overwrite part of the subclass.
这篇关于为什么使用此POD结构作为基类是危险的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!