Why passing a static in-class initialized member t

2019-04-29 11:47发布

问题:

This is based on the original question that was asked here.

[Detailed]: Here is the relevant question as requested in comments

Lippman's c++ primer on p.303 mentions:

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 why does passing Account::period to a function that takes a const int&, needs that period must be defined?
It will be very helpful to know,

  • What is the rationale?
  • Does the standard explicitly specify these scenarios or these are deduced from a more generic quotation?

回答1:

If the member never has it's address taken (or, equivalently, a reference bound to it), the compiler can simply use it's value, and this value is the same in every TU, so there's no problem because rvalues don't have to have addresses. Or it can make a copy in each TU or whatever it wants, because you can't observe it's address.

But if you attempt to take the address, the compiler has an obligation to make sure that in all TUs, the address is the same. Because of C++'s truly horrendous TU system, this means needing one, and only one, explicit definition.



回答2:

I would imagine the rationale to be something along the lines of:

const int* get_addr(const int& i) {
  return &i;
}

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

  const int* period_ptr() {
    return get_addr(period);
  }
}


标签: c++ c++11 static