Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why passing a static in-class initialized member to a function taking const reference needs the member to have a definition?

Tags:

c++

static

c++11

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?
like image 260
Alok Save Avatar asked Jan 27 '13 13:01

Alok Save


1 Answers

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.

like image 171
Puppy Avatar answered Oct 24 '22 10:10

Puppy