#Default destructor behavior

24 messages · Page 1 of 1 (latest)

haughty sorrel
#

Imagine a class like this:

class Item {
    int* number_ptr;
    public:
        Item() = default;
        Item(int* number_ptr): number_ptr(number_ptr){}
        ~Item() = default;
};

Does the default destructor also delete all the pointer members of the class or do I have to manually delete them?

wooden spruceBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

keen veldt
floral terrace
#

the defaulted destructor simply destroys all the members.

#

how would it even know that it needs to delete these?

haughty sorrel
#

idk if it pointed out to an address maybe?

floral terrace
#

?

haughty sorrel
#

then again it can't distinguish an address and a normal int by value

#

so that's incorrect

floral terrace
#

there's no way for the compiler to know whether you'd want something to be deleted there or not.

haughty sorrel
#

yeah you're right

#

So imagine if something like this was written:

int h{20};
int* h_ptr = &h;
Item item{h_ptr};

would having a delete number_ptr; in the destructor alter h_ptr?

#

since you're passing the same pointer?

keen veldt
#

No object was created with new, so you wouldn't call delete

haughty sorrel
#

so as long as there's no new involved you don't use delete at all?

#

Good to know, ty

#

!close

wooden spruceBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity

floral terrace
haughty sorrel
#

Alright so I wasn't messing it up

#

I thought maybe I had to manually delete the non-new pointers

glacial heron
#

Just making sure, you do know what smart pointers are, right?

because std::unique_ptr does exactely this.

haughty sorrel
#

Yeah