gpt4 book ai didi

c++ - 关于静态数据成员类内初始化的困惑

转载 作者:可可西里 更新时间:2023-11-01 16:39:35 25 4
gpt4 key购买 nike

我正在阅读 lippman 的 c++ primer,第 1 页。 303 他们给了这个:

class Account {
private:
static constexpr int period = 30;
double daily_tbl[period];
}

If the member is used only in contexts where the compiler can substitute the member's value, then an initialized const or constexpr static need not be separately defined. However, if we use the member in a context in which the value cannot be substituted, then there must be a definition for that member.

还有:

For example, if we pass Account::period to a function that takes a const int&, then period must be defined.

所以我尝试添加这样一个功能:

class Account {
private:
static constexpr int period = 30;
double daily_tbl[period];

void foo(const int &i) { ; }
void bar() { foo(period); } //no error?
};

我添加了一个接受 const int& 的函数。我也没有为 period 变量添加任何定义。但我仍然没有得到任何错误,正如他们所说的那样。为什么不呢?

最佳答案

违反此规则不需要诊断。所以行为实际上是未定义的。

我认为不需要诊断的原因是链接器会给出诊断。当编译器优化访问时(在这种情况下可能发生),链接器不再注意到任何错误。仍然注意到此错误将需要在链接器中对整个程序进行分析,以便它可以访问原始未优化的源代码表示。这会增加编译时间并需要高级链接器和编译器。

关于c++ - 关于静态数据成员类内初始化的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14547370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com