为什么将静态类内初始化成员传递给一个带有const引用的函数需要该成员有一个定义? [英] Why passing a static in-class initialized member to a function taking const reference needs the member to have a definition?

查看:100
本文介绍了为什么将静态类内初始化成员传递给一个带有const引用的函数需要该成员有一个定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是根据提出的原始问题 这里



[详细]:这是评论中请求的相关问题 >

pp.303上的Lippman的c ++底层提到:

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




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


另外:


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


那么为什么将 Account :: period const int& 需要定义 period




  • 理由是什么?

  • 标准是否明确指定这些情况或从更通用的引用中推导出这些情况?


解决方案

如果成员从来没有采用它的地址(或者等效地绑定到它的引用),编译器可以简单地使用它的值,并且这个值在每个TU中是相同的,没有问题,因为右值不必有地址。



但是如果你试图获取这个地址,编译器会自动生成一个地址,有义务确保在所有TU中,地址是相同的。由于C ++的真正可怕的TU系统,这意味着需要一个,只有一个明确的定义。


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?

解决方案

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.

这篇关于为什么将静态类内初始化成员传递给一个带有const引用的函数需要该成员有一个定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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