加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

sizeof()是否显示C类开销?

发布时间:2020-12-16 10:23:11 所属栏目:百科 来源:网络整理
导读:#include iostreamusing namespace std;class Test { int a;public: int getA() { return a; }Test(): a(1){}Test(int i): a(i){}};int main() { Test t1(100); cout sizeof(t1) " " sizeof(1) endl; // 4 4 return 0;} 似乎c中的类根本没有开销. t1的大小为
#include <iostream>
using namespace std;

class Test {
    int a;
public:
    int getA() {
        return a;
    }

Test(): a(1){}
Test(int i): a(i){}

};



int main() {
    Test t1(100);
    cout << sizeof(t1) << " " << sizeof(1) << endl; // 4 4
    return 0;
}

似乎c中的类根本没有开销. t1的大小为4,类似于整数.如果我将另一个int成员添加到Test,它会将其大小增加到8.

我本来期望的东西大于4

类没有开销是真的吗?

解决方法

It seems that classes in c++ have no overhead at all.

只要一个类没有虚函数,那么,是的.你期望什么样的开销?无虚拟类仅仅是变量的集合,具有与该类型相关联的一组函数.

class Foo {
    int a;
    int bar() const { return a*a; }
};

可以简单地替换为

struct Foo {
    int a;
}

int Foo_bar(Foo const *that) {
    return (that->a) * (that->a);
}

如果您编译了每个片段,您会看到汇编代码看起来几乎是同一个.

但是,如果添加一个虚拟功能,游戏会发生巨大变化.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读