class Base
{
private:
int nID;
friend int fnDeleteBase(Base* base);
public:
Base( int baseID):nID(baseID) { cout << "Base Constructed with value" << endl; }
Base () : nID(5){cout << "Base Constructed WITHOUT value" << endl; }
~Base() { cout << "Base class object killed " << endl; }
};
int fnDeleteBase(Base* base) // Line 1
{
delete base; // Line 2 - important
cout << "Base object deleted " << endl;
return (1);
}
int main()
{
Base aBase; // Line 3
try
{
int i = fnDeleteBase(&aBase); // Line 4
}
catch(...)
{
cout << "Exception handled " << endl;
}
return (0);
}
上面的代码片段我正在调试。我无法进入正在删除基本对象的第 2 行。一旦我尝试进入或运行第 2 行,控件就会消失,我必须终止调试或执行
我得到的输出是:
Base Constructed (any of the construction is valid)
Base class Object killed
但是一切正常,如果将第 3 行更改为 Base * aBase = new Base();
.控制台上的输出为:
Base Constructed (any of the construction is valid)
Base class Object killed
Base object Deleted
有人可以分享两者背后的技术细节吗?
您应该只在使用new
构造的指针上使用delete
(或分配给使用 new
构造的其他指针的指针(,没有例外(我知道(。
在其他任何情况下使用 delete
(这是在第一种情况下发生的情况,因为 fnDeleteBase
的参数是指向 Base aBase
的指针,它不是指针,那里没有new
关键字(会导致未定义的行为。
解释编译器的确切作用并没有真正的帮助,因为对于未定义的行为,这可能因编译器而异。应该不惜一切代价避免这种情况。