c++ - 我不明白为什么 'Derived1' 需要与 'Derived3' 相同的内存量

标签 c++ oop

在下面的代码中,我不明白为什么“Derived1”需要与“Derived3”相同的内存量。另外Derived 4的size为16有没有什么特殊意义。

#include <iostream>
using namespace std;

class Empty
{};

class Derived1 : public Empty
{};

class Derived2 : virtual public Empty
{};

class Derived3 : public Empty
{    
    char c;
};

class Derived4 : virtual public Empty
{
    char c;
};

class Dummy
{
    char c;
};

int main()
{
    cout << "sizeof(Empty) " << sizeof(Empty) << endl;
    cout << "sizeof(Derived1) " << sizeof(Derived1) << endl;
    cout << "sizeof(Derived2) " << sizeof(Derived2) << endl;
    cout << "sizeof(Derived3) " << sizeof(Derived3) << endl;
    cout << "sizeof(Derived4) " << sizeof(Derived4) << endl;    
    cout << "sizeof(Dummy) " << sizeof(Dummy) << endl;

    return 0;
}

这段代码的输出是:

sizeof(Empty) 1
sizeof(Derived1) 1
sizeof(Derived2) 8
sizeof(Derived3) 1
sizeof(Derived4) 16
sizeof(Dummy) 1

最佳答案

classsizeof 必须为 1 或更大,否则指针运算会严重中断,并且 class 的数组元素会都占用相同的内存。

因此 sizeof(Derived1) 至少为 1,sizeof(Empty) 也是如此。 空基优化 意味着派生类的大小实际上为零。

sizeof(Derived3) 也可以是 1,因为单个成员是 char。请注意,编译器在这里再次利用空基优化

多态 类(即那些包含 virtual 关键字的类)具有更大的大小,因为您的编译器实现了多态行为的要求。

关于c++ - 我不明白为什么 'Derived1' 需要与 'Derived3' 相同的内存量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51380901/

相关文章:

c++ - 带有 std::thread 和 this 的 ctor 初始值设定项列表

c++ - 在 C++ 中制作 shell,尝试创建 shell 变量

c++ - 不同 boost 图的相同权重

excel - 类模块中是否需要 Me 关键字?

java - 为什么在Java链表遍历中使用递归不能返回Object?

c++ - 当一个单独的应用程序写入日志文件时从日志文件中读取数据

C++ 应用程序在崩溃后运行缓慢(MSVS、Win8 x64)

php - 在 PHP 中实例化对象后立即使用对象运算符

c++ - 为什么 '&' 会改变对象的行为?

api - REST 会破坏数据封装吗?