没有在类中使用const静态变量进行优化吗? [英] not used const static variable in class optimized out?

查看:54
本文介绍了没有在类中使用const静态变量进行优化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

合理的体面的编译器能否丢弃此const静态变量

Can a reasonable decent compiler discard this const static variable

class A{
     const static int a = 3;
}

如果编译后的二进制文件中没有使用它,或者二进制文件中仍然显示它?

if it is nowhere used in the compiled binary or does it show up anyway in the binary?

推荐答案

简短答案:也许可以.该标准没有说如果从未使用过编译器,则它必须保留常量(或字符串,函数,或其他任何东西).

Short answer: Maybe. The standard does not say the compiler HAS to keep the constants (or strings, or functions, or anything else), if it's never used.

长答案:这在很大程度上取决于具体情况.如果编译器可以清楚地确定未使用它,它将删除未使用的常量.如果无法确定,则无法删除未使用的常量,因为该常量可能会被编译器当前未知的东西(例如另一个源文件)使用.

Long answer: It very much depends on the circumstances. If the compiler can clearly determine that it is not used, it will remove unused constants. If it can't make that determination, it can not remove the unused constant, since the constant COULD be used by something that isn't currently known by the compiler (e.g. another source file).

例如,如果 class A 在函数内部,则编译器可以知道该类未在其他地方使用,并且如果该常数未在函数中使用,则它在任何地方都不会使用.如果该类位于全局"空间中,以便可以在其他地方使用它,则它将需要保持常量.

For example, if class A is inside a function, the compiler can know this class is not used elsewhere, and if the constant isn't used in the function, then it's not used anywhere. If the class is in a "global" space, such that it could be used somewhere else, then it will need to keep the constant.

通过整个程序优化"或链接时间优化"(从现在开始都称为LTO),这变得更加有趣,其中所有代码实际上都被优化为一个大块,当然,二手"或可以确定所有可能的用途.

This gets even more interesting with "whole program optimization" or "link time optimization" (both from now on called LTO), where all the code is actually optimized as one large lump, and of course, "used" or "not used" can be determined for all possible uses.

您可以想象,结果还取决于编译器(以及LTO的链接器)的智能程度.所有编译器都应遵循如有疑问请保留"的原则.

As you can imagine, the result will also depend on how clever the compiler (and linker for the LTO) is. All compilers should follow the principle of "if in doubt keep it".

您当然可以进行实验,并在使用该变量的地方编写一些代码,然后删除该使用,然后查看它对汇编代码有何不同(例如, g ++ -S x.cpp clang ++ -S x.cpp ,然后查看生成的xs文件).

You can of course experiment, and write some code where you use the variable, and then remove the use, and see what difference it makes to the assembly code (e.g. g++ -S x.cpp or clang++ -S x.cpp, and look at the resulting x.s file).

这篇关于没有在类中使用const静态变量进行优化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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