简体   繁体   English

与它所属的类相同类型的对象数组会创建无限实例吗?

[英]Would an array of the same type of objects as the class it is a member of create infinite instances?

Sorry for the awkward wording of the question but I'm not sure how to describe it better in words so I'll try an example 很抱歉这个问题的措词不好,但是我不确定如何用语言更好地描述它,所以我将尝试一个例子

struct A {
    A* a;
    A() {a = new A[2];}
    ~A() {delete[] a;}
}

int main() {
    A aa;
}

Once aa gets constructed, the *a internal to struct A will be allocated an array of two A objects. 一旦构造了aastruct A*a内部将被分配一个包含两个A对象的数组。 But it appears to me that each of those objects will, in turn, create an array of A objects of their own as a result of the default constructor, and on and on in a seemingly endless cycle. 但是在我看来,由于默认构造函数的作用,每个对象将依次创建一个自己的A对象数组,并且似乎不断循环。 Am I correct in thinking this? 我认为正确吗?

Am I correct in thinking this? 我认为正确吗?

Yes. 是。 The constructor is called recursively, and you'll probably run out of dynamic storage or overflowing the call stack at some point. 构造函数被递归调用,您可能会耗尽动态存储空间或在某个时候溢出调用堆栈。

Yes, you are absolutely right. 是的,您绝对正确。 Your code effectively embeds an array of objects inside itself. 您的代码有效地在其内部嵌入了一组对象。 Essentially, you are making this impossible struct : 本质上,您正在使这个不可能的struct

struct A {
    A a[2]; // Impossible
};

Your code bypasses compiler's check for by using pointers, so the code crashes at runtime due to infinite recursion. 您的代码使用指针绕过了编译器的检查,因此由于无限递归,代码在运行时崩溃。

If you would like to make A that refers to two A s optionally, make an array of two pointers. 如果要使A可选地引用两个A ,则使一个包含两个指针的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM