【发布时间】:2015-10-28 19:53:27
【问题描述】:
此代码编译并运行。 (运行风险自负)。当它运行时,它会无休止地打印“Constr beg”,正如可以预测的那样。我的问题是,递归是创建一个对象还是多个对象?如果创建了多个对象,当'this'指针被用作构造函数参数时会发生什么?
#include <iostream>
using namespace std;
class A {
private:
A* m_p;
public:
A() = delete;
A(A* m_p) {
cout << "Constr beg" << endl;
m_p = new A{this};
cout << "Constr end" << endl;
}
~A() {
cout << "Destr beg" << endl;
if (m_p != nullptr) {
delete this;
}
cout << "Destr end" << endl;
}
};
int main()
{
// A a(A&);
A* pA{nullptr};
A b(pA);
return 0;
}
【问题讨论】:
-
愚蠢的代码 - 任何人都无法回答这个问题
标签: c++ recursion constructor this