是内存分配给一个静态常量变量,其地址从未使用过? [英] Is memory allocated for a static const variable whose address is never used?

查看:166
本文介绍了是内存分配给一个静态常量变量,其地址从未使用过?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我从来没有使用一个静态常量变量的地址,是内存使用它一个合理的现代编译器时分配的?

If I never use the address of a static const variable, is memory allocated for it when using a reasonably modern compiler?

推荐答案

这取决于变量的类型,以及是否恒也意味着不断前pression。例如:

It depends on the type of the variable, and on whether "constant" also means "constant expression". Example:

static const Foo = get_foo(std::cin);

static const int q = argc * 3;

static const std::string s(gets());

这些变量是常量,而是明目张胆地需要一个实际的分配。

These variables are const, but blatantly need an actual allocation.

在另一方面,下面的常量的前pression 的可能永远不会有物理存储:

On the other hand, the following constant expression may never have physical storage:

static const int N = 1000;

static const std::shared_ptr<void> vp();  // constexpr constructor!

更重要的是,静态constexpr的成员的,如果你仔细的变量不需要一个定义:

Most importantly, static constexpr member variables don't need a definition if you're careful:

struct Bar
{
  int size() const { return N; }
  static const int N = 8;
};
// does NOT need "const int Bar::N;"

这篇关于是内存分配给一个静态常量变量,其地址从未使用过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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