是否为永远不会使用地址的静态const变量分配内存?

Emi*_*son 8 c c++ optimization static const

如果我从不使用静态const变量的地址,那么在使用合理的现代编译器时是否为它分配了内存?

Ker*_* SB 10

它取决于变量的类型,以及"常量"是否也意味着"常量表达".例:

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

static const int q = argc * 3;

static const std::string s(gets());
Run Code Online (Sandbox Code Playgroud)

这些变量是常量,但显然需要实际分配.

另一方面,以下常量表达式可能永远不会有物理存储:

static const int N = 1000;

static const std::shared_ptr<void> vp();  // constexpr constructor!
Run Code Online (Sandbox Code Playgroud)

最重要的是,如果您小心,静态constexpr 成员变量不需要定义:

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

  • 第二个例子(`q`)可能不需要内存位置,具体取决于它的使用位置. (2认同)