本文介绍了是否允许编译器优化私有数据成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果编译器可以证明从未使用过某个类的(私有)成员,包括潜在的朋友,那么该标准是否允许编译器从该类的内存占用中删除该成员?

If the compiler can prove that a (private) member of a class is never used, including by potential friends, does the standard allow the compiler to remove this member from the memory footprint of the class?

不言而喻,在编译时,这对于受保护的成员或公共成员而言是不可能的,但是在某些情况下,可能需要私人数据成员来构造这样的证据.

It is self-evident that this not possible for protected or public members at compile time, but there could be circumstances where it is possible regarding private data members for such a proof to be constructed.

相关问题:

  • Behind the scenes of public, private and protected (sparked this question)
  • Is C++ compiler allowed to optimize out unreferenced local objects (about automatic objects)
  • Will a static variable always use up memory? (about static objects)

推荐答案

理论上可能(以及未使用的公共成员),但不适用于我们习惯的那种编译器生态系统(针对可以单独链接的固定ABI编译的代码).删除未使用的成员只能通过禁止单独的库的整个程序优化来完成 .

Possible in theory (along with unused public members), but not with the kind of compiler ecosystem we're used to (targeting a fixed ABI that can link separately-compiled code). Removing unused members could only be done with whole-program optimization that forbids separate libraries.

其他编译单元可能需要在 sizeof(foo)上达成共识,但是如果依赖于验证没有成员函数的行为的实现依赖于任何私有成员.

Other compilation units might need to agree on sizeof(foo), but that wouldn't be something you could derive from a .h if it depended on verifying that no implementation of a member function's behaviour depended on any private members.

请记住,C ++仅真正指定一个程序,而不是一种编写库的方法.ISO C ++指定的语言与我们习惯(当然)的实现样式兼容,但是实现一次获取所有 .cpp .h 文件的实现并生成单个自包含的不可扩展的可执行文件.

Remember C++ only really specifies one program, not a way to do libraries. The language ISO C++ specifies is compatible with the style of implementation we're used to (of course), but implementations that take all the .cpp and .h files at once and produce a single self-contained non-extensible executable are possible.

如果您对实施进行了足够的限制(没有固定的ABI),则可能会按规则将整个程序应用于积极的应用程序.

脚注1:我将添加""或以某种方式将大小信息导出到正在编译的其他代码".如果允许编译器已经看到类中声明的每个成员函数的定义,则作为允许库的一种方式.但是@PasserBy的答案指出,单独编译的库可能是以最终产生外部可见副作用(例如I/O)的方式使用声明的私有成员的东西.因此,我们必须完全排除它们.

Footnote 1: I was going to add "or exports the size information somehow to other code being compiled" as a way to allow libraries, if the compiler could already see definitions for every member function declared in the class. But @PasserBy's answer points out that a separately-compiled library could be the thing that used the declared private members in ways that ultimately produce externally-visible side effects (like I/O). So we'd have to fully rule them out.

鉴于这种优化的目的,公共和私人成员是等效的.

这篇关于是否允许编译器优化私有数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 06:52