拥有对自身的引用的类 [英] Class that holds a reference to itself

查看:77
本文介绍了拥有对自身的引用的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

跳过标准草案(n3242),我在第9.2条(强调我的意思)中找到了这句话:

Skimming through the standard draft (n3242) I found this sentence in Clause 9.2 (emphasis mine):

非静态(9.4)数据成员不应具有不完整的类型.在 特别是,C类不得包含该类的非静态成员 C,但它可以包含指向类对象的指针或引用 C.

Non-static (9.4) data members shall not have incomplete types. In particular, a class C shall not contain a non-static member of class C, but it can contain a pointer or reference to an object of class C.

据此,我认为定义这样的类是很好的:

From this I argue that is fine to define a class like this:

class A {
public:
  A(A& a) : a_(a){
  }
private:
  A& a_;
};

然后在第8.3.2节中,我找到了以下内容:

Then in clause 8.3.2 I found the following:

引用应初始化为引用有效对象,或 功能

问题1:是否可以通过将其名称作为引用来定义这种类型的对象:

Question 1: Is it permitted to define an object of this type passing its name as a reference:

A a(a);

还是会触发未定义的行为?

or will this trigger undefined behavior?

问题2:如果是,那么标准的哪些部分允许初始化仍在构造的对象中的引用?

Question 2: If yes, what are the parts of the standard that permit the initialization of the reference from a still-to-be-constructed object?

问题3:如果否,是否表示A类的定义格式正确,但是在不触发UB的情况下不能创建 first 对象?在这种情况下,背后的原因是什么?

Question 3: If no, does this mean the definition of class A is well formed but no first object can be created without triggering UB? In this case what is the rationale behind this?

推荐答案

有效对象"未在标准中的任何位置定义,但其意图是表示一个具有适当大小和对齐方式的内存区域,可以包含一个对象.指定的类型.它只是意味着排除对诸如已取消引用的空指针,未对齐的内存区域等内容的引用.未初始化的对象是有效的.

"valid object" is not defined anywhere in the standard, but it is intented to mean a region of memory with appropriate size and alignment that can contain an object of the specified type. It just means to exclude references to such things as dereferenced null pointers, misaligned regions of memory, etc. An uninitialised object is valid.

CWG 453 a>.

这篇关于拥有对自身的引用的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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