混淆关于静态数据成员的类的初始化 [英] Confusion about in-class initialization of static data members

查看:114
本文介绍了混淆关于静态数据成员的类的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读lippman的c ++引文,其中p。 303他们给这:

I'm reading lippman's c++ primer where on p. 303 they give this:

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




如果成员仅用于上下文编译器可以替换成员的值,那么初始化的const或constexpr static不需要单独定义。但是,如果我们在值不能被替换的上下文中使用成员,则必须有该成员的定义。

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.

另外:


例如,如果我们将Account :: period传递给一个使用const int& amp的函数, 。

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

所以我试着添加这样的函数:

So I tried adding such a function:

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

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

在这里我添加了一个函数,我也没有添加任何定义的周期变量。但仍然没有得到任何错误,因为他们说我应该得到。为什么不呢?

There I have added a function that takes a const int&. I also did not add any definition for the period variable. But still I get no error, as they said I should get. Why not?

推荐答案

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

A violation of this rule does not require a diagnostic. So behavior is effectively undefined.

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

I think that the reason this is not required to be diagnosed is because the diagnostic would be given by the linker. And when the compiler optimizes the accesses away (as it probably happened in this case), the linker cannot notice anything wrong anymore. Still noticing this error would require whole program analysis in the linker so that it has access to the original unoptimized source code representation. This increases compile time and requires an advanced linker and compiler.

这篇关于混淆关于静态数据成员的类的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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