如果您为 class 的一个对象动态分配内存作为参数,会发生什么情况?

What will be happen if you dynamically allocates memory for one object of the class as an argument?

class Example
{
  private:
   Example* pointer;
   Example* pointer2;
  public:
   Example();
   void setPointer2(Example* object);
};

Example::Example()
{
  pointer = new Example();
}

void Example::setPointer2(Example* object)
{
  this->pointer2 = object;
}

int main()
{
  Example object;
  object.setPointer2(new Example());

  return 0;
}

删除不重要。我只想知道这两个对象之间的区别是指针和 pointer2 持有的地址。他们分配不同吗?实际问题是,在哪里使用 "new" 运算符重要吗?

代码中的一个主要问题是无限递归!您定义的构造函数:

Example::Example()
{
  pointer = new Example();
}

创建一个自己类型的新对象。这将调用构造函数(再次),该调用将调用构造函数(一次又一次...)

但是,除了这个问题,您是通过直接将地址分配给 pointer 来创建 new 对象,还是在其他地方创建对象然后将其分配给它并不重要地址(稍后)到 pointer2。两者都将指向 class.

的对象