我正在尝试按特定顺序输出对象的创建和删除。默认情况下,首先使用构造函数的析构函数会创建第一个对象,依此类推,然后析构函数会从最后创建的对象开始删除。我正在尝试更改输出顺序,类似于以下内容:
Object 1 is created, we've got 1 object(s) now!
Object 2 is created, we've got 2 object(s) now!
Object 3 is created, we've got 3 object(s) now!
Object 3 is deleted, we've got 2 object(s) now!
Object 2 is deleted, we've got 1 object(s) now!
Object 4 is created, we've got 2 object(s) now!
Object 4 is deleted, we've got 1 object(s) now!
Object 1 is deleted, we've got 0 object(s) now!
代码:
class Object {
public:
Object(int i) {
id = i;
count++;
cout<<"Object "<<id<<" is created, we've got "<<count<<" object(s) now!"<<endl;
}
~Object() {
count--;
cout<<"Object "<<id<<" is deleted, we've got "<<count<<" object(s) now!"<<endl;
}
private:
int id;
static int count;
};
为此,我发现我可以使用指针,指向创建的对象,并删除,当我们需要时,可以通过这种方式控制创建和删除的顺序。
#include"Object.h"
extern void TestObjects()
{
Object *a;
Object obj1(1),obj2(2),obj3(3);
a = &obj3;
delete a;
Object *c;
c = &obj2;
delete c;
}
现在,它仅创建3个对象,并在创建后立即删除第三个对象,而我正在尝试删除第三个对象之后删除第二个对象。
答案 0 :(得分:3)
您使用delete
是无效的,从而导致未定义的行为,因为您没有使用new
创建对象。您正在尝试销毁堆栈上存在的对象,这些对象在超出范围时会被自动销毁,您无权手动销毁它们。
如果要使用delete
控制销毁顺序,则必须使用new
,如下所示:
void TestObjects()
{
Object *obj1 = new Object(1);
Object *obj2 = new Object(2);
Object *obj3 = new Object(3);
delete obj3;
delete obj2;
Object *obj4 = new Object(4);
delete obj4;
delete obj1;
}
或者,在您的特定示例中,可以通过简单地更多地控制对象的范围而完全不使用new
和delete
来获得相同的输出:
void TestObjects()
{
Object obj1(1);
{
Object obj2(2);
Object obj3(3);
} // <-- obj3 and obj2 are destroyed here, in that order!
Object obj4(4);
} // <-- obj4 and obj1 are destroyed here, in that order!