我何时可以确定constexpr全局变量将像C宏一样被“忘记"? [英] When can I be sure a constexpr global variable will be "forgotten", like a C macro?

查看:231
本文介绍了我何时可以确定constexpr全局变量将像C宏一样被“忘记"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用全局constexpr变量:

constexpr int foo = 123;

代替C宏:

#define FOO (123)

在我正在编写的某些代码中.从某种意义上说,我想保证这是相同的行为,即它不会在运行时占用内存中的空间,也不会在已编译的目标代码中可见/存在(也就是说,它的值将用作立即位置)相关).

in some code I'm writing. I would like to be guaranteed the same behavior, in the sense that this will not take up space in memory at runtime, nor will it be visible/exist in the compiled object code (that is, its value will be used as an immediate where relevant).

我可以完全获得此保证吗?在某些情况下?当然,假设我不是要使用x的地址或任何此类有趣的生意.

Can I get this guarantee at all? Under some conditions? Assume, of course, I'm not trying to use x's address or any such funny business.

推荐答案

C ++标准不保证在运行时占用内存或目标文件的内容.

The C++ standard does not make any guarantees about taking space in memory at runtime, or the contents of object files.

constexpr int foo = 123;表示foo具有内部链接,并且在每个可见此行的转换单元中,都有一个静态存储持续时间为sizeof(int)个字节的对象.

constexpr int foo = 123; at namespace scope means that foo has internal linkage, and in each translation unit that this line is visible, there is an object with static storage duration, of sizeof(int) bytes.

如果程序的输出不取决于存储是否实际存在,则允许但不要求编译器优化此存储. (这称为按条件规则.)

The compiler is permitted, but not required, to optimize out this storage if the output of the program does not depend on whether the storage actually exists. (This is called the as-if rule).

一个可能会优化存储的示例是,如果您有一个功能:

An example of where the storage probably would not be optimized out would be if you had a function:

int const *bar() { return &foo; }


在实践中:


In practice:

  • 如果foo不是 odr-used ,那么它将不会在运行时占用内存.
  • 很有可能 foo的名称不会出现在目标文件中,因为它具有内部链接.
  • it is very likely that if foo is not odr-used then it will not occupy memory at runtime.
  • it is very likely that foo's name will not appear in an object file, since it has internal linkage.

这篇关于我何时可以确定constexpr全局变量将像C宏一样被“忘记"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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