Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

c++ - Confusion about in-class initialization of static data members

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];
}

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.

Also:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...