C ++是否可以通过编译器在类外优化常量类数据? [英] C++ Can constant class data be optimized out of class by compiler?

查看:104
本文介绍了C ++是否可以通过编译器在类外优化常量类数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道类外部的常量变量可以由编译器直接优化为函数调用,但是对于常量类变量而言,编译器执行相同操作合法吗?

I know that constant variables outside classes can be optimized directly into function calls by the compiler, but is it legal for the compiler to do the same for constant class variables?

如果有一个这样声明的类:

If there is a class declared like this:

class A {
public:
const int constVar;
    //other, modifiable variables

A(int val): constVar(val) {
         //code to initialize modifiable variables

}
};

然后我创建一个A的实例,并调用如下函数:

and I create an instance of A and call a function like this:

A obj(-2);
int absoluteVal = std::abs(A.constVar);

是否允许编译器执行此操作,并使类缩小为sizeof(int)?:

is the compiler allowed to do this instead and make the class be sizeof(int) smaller?:

A obj();
int absoluteVal = std::abs(-2);

推荐答案

编译器可以自由发出任何保留程序可观察到的行为"的代码(复制构造函数有一个例外,即使该例外也可以被忽略)具有可观察到的行为,但不适用于此处).这称为好像规则

The compiler is free to emit any code that preserves the "observable behavior" of the program (there is an exception with copy constructor which can be elided even if it has observable behavior, but it doesn't apply here). This is called the as if rule

struct X { int x; };

auto foo()
{
  X x{24};

  return x.x;
}

任何体面的编译器都会对此进行优化:

any decent compiler will optimize the above to this:

foo():                                # @foo()
        mov     eax, 24
        ret

如您所见,它与constness(好吧,几乎)没有任何关系,只是与可观察到的行为有关.您可以尝试增加代码的复杂性,看看编译器在弄清楚它可以删除与类实例相关的代码方面有多聪明.提示:这很聪明.

As you can see, it doesn't have anything to do with constness (well, almost), just with observable behavior. You can try and play with the code adding in complexity and see how smart is the compiler in figuring out it can remove the code related to the class instance. Hint: it is very smart.

我不清楚您的意思是什么

Is not clear to me what you mean by this:

是否允许编译器执行此操作,并使类成为 sizeof(int)较小?:

is the compiler allowed to do this instead and make the class be sizeof(int) smaller?:

我可以告诉你:对于类型X和类型sizeof(x)的对象x始终为= sizeof(X),而不管类的实例化如何.换句话说,类的大小是在定义类时确定的,因此它不受可能的实例化或缺少实例化的影响.类的大小是其非静态数据成员的所有大小加上填充的总和.填充是由实现定义的,通常可以对其进行某种程度的控制(例如,打包结构).因此,不能,一个类的大小永远不能小于其所有非静态非引用数据成员的大小之和.

I can tell you that: for a type X and an object x of such type sizeof(x) is always = sizeof(X) regardless of instantiations of the class. In other words the size of the class is determined when the class is defined, and as such it is not influenced by possible instantiations or lack of. The size of a class is the sum of all the sizes of its non-static data members plus padding. The padding is implementation defined and can be usually be somewhat controlled (e.g. packed structs). So no, the size of a class can never be smaller than the sum of the sizes all it's non-static non-reference data members.

这篇关于C ++是否可以通过编译器在类外优化常量类数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆