简体   繁体   中英

How to use pointer with objects; Constructors and Destructors. C++

I'm trying to make an output of creation and deletion of an object in specific order. Using constructors destructors by default first it creates the first object and so on, and destructor starts deletion from last created object. I'm trying to change the output order something similar to this:

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!  

Code:

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;
};  

In order to do that i found out that i can use pointers, pointing to the created object and delete that when we want, in this way we can control the order of creation and deletion.

#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;

    }

Till now it only creates 3 objects and deletes the third one immediately after creation, and I'm trying to delete the second right after the deletion of third.

Your use of delete is invalid, causing undefined behavior , because you are not using new to create the objects. You are trying to destroy objects that exist on the stack and are destroyed automatically when they go out of scope, you have no right to destroy them manually.

If you want to use delete to control destruction order, you MUST use new , like this:

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;
}

Live Demo

Alternatively, in your particular example, it is possible to get the same output by simply taking more control of the objects' scopes and not using new and delete at all:

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!

Live Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM