创建了一个简单的类来测试删除对象,这个函数将从另一种语言调用,但我遇到了一些我无法解释的奇怪问题。
我的类包含可以销毁它实例的函数,并将指针设置为null
。
1 。在主要功能中使用delete
时,会调用
using namespace std;
//Forward declaration:
class Motor;
void DestroyMotor(Motor** motor)
{
if (motor != nullptr)
{
//(*motor)->~Motor();
delete *motor;
*motor = nullptr;
}
}
void DestroyMotor(Motor*& motor)
{
delete motor;
motor = nullptr;
}
class Motor
{
public:
Motor();
~Motor();
private:
};
Motor::Motor()
{
cout << "Motor Created" << endl;
}
Motor::~Motor()
{
cout << "Motor Destroyed" << endl;
}
int main()
{
{
Motor *myMotor = new Motor();
if (myMotor == nullptr)
cout << "IS null" << endl;
else
cout << "NOT null" << endl;
delete myMotor;
myMotor = nullptr;
if (myMotor == nullptr)
cout << "IS null" << endl;
else
cout << "NOT null" << endl;
}
cin.get();
return 0;
}
输出:
- Motor Created
- 非null
- 马达被毁坏
- IS null
2 。在其中一个delete
函数中使用DestroyMotor
时, NOT 调用了构造函数(错误?):
int main()
{
{
Motor *myMotor = new Motor();
if (myMotor == nullptr)
cout << "IS null" << endl;
else
cout << "NOT null" << endl;
//Free myMotor;
//DestroyMotor(myMotor);
DestroyMotor(&myMotor);
if (myMotor == nullptr)
cout << "IS null" << endl;
else
cout << "NOT null" << endl;
}
cin.get();
return 0;
}
输出:
- Motor Created
- 非null
- IS null
3 。如果我将类移到这两个DestroyMotor
函数的顶部并且现在正在调用析构函数,则修复#2 中的问题
using namespace std;
class Motor
{
public:
Motor();
~Motor();
private:
};
Motor::Motor()
{
cout << "Motor Created" << endl;
}
Motor::~Motor()
{
cout << "Motor Destroyed" << endl;
}
void DestroyMotor(Motor** motor)
{
if (motor != nullptr)
{
//(*motor)->~Motor();
delete *motor;
*motor = nullptr;
}
}
void DestroyMotor(Motor*& motor)
{
delete motor;
motor = nullptr;
}
int main()
{
{
Motor *myMotor = new Motor();
if (myMotor == nullptr)
cout << "IS null" << endl;
else
cout << "NOT null" << endl;
//delete myMotor;
//myMotor = nullptr;
//Free myMotor;
//DestroyMotor(myMotor);
DestroyMotor(&myMotor);
if (myMotor == nullptr)
cout << "IS null" << endl;
else
cout << "NOT null" << endl;
}
cin.get();
return 0;
}
输出:
- Motor Created
- 非null
- 马达被毁坏
- IS null
任何人都可以解释#2到底发生了什么,以及为什么将课程移到顶层解决问题?我的意思是,我使用了前瞻性声明,但从未解决过这个问题。