G
Gonçalo Rodrigues
Hi all,
I am a little confused about the delete operator, so I have a
question. Suppose we have something like
class Base {
public:
void* operator new(std::size_t size);
void operator delete(void* ptr);
//The rest goes here.
}
class Derived : public Base {
public:
void* operator new(std::size_t size);
void operator delete(void* ptr);
//The rest goes here.
}
Derived* der = new Derived;
Base* base = der; //Implicit upcast.
delete base;
In this case, it is the static type of the pointer that matters, so it
is the Base delete operator that gets called. In fact, by the time
delete is called the object has already been "demoted" to void* -
there is no concept of dynamic type to speak of. Am I correct?
And if the answer is yes, how do I organize things such that the
Derived delete gets called?
The use case I have is of a single-root hierarchy of heap-allocated
objects handled via smart pointers. The root operator new and delete
is just a general-purpose allocator but each class can have (and it
often does) its own special allocators.
TIA, best regards,
G. Rodrigues
I am a little confused about the delete operator, so I have a
question. Suppose we have something like
class Base {
public:
void* operator new(std::size_t size);
void operator delete(void* ptr);
//The rest goes here.
}
class Derived : public Base {
public:
void* operator new(std::size_t size);
void operator delete(void* ptr);
//The rest goes here.
}
Derived* der = new Derived;
Base* base = der; //Implicit upcast.
delete base;
In this case, it is the static type of the pointer that matters, so it
is the Base delete operator that gets called. In fact, by the time
delete is called the object has already been "demoted" to void* -
there is no concept of dynamic type to speak of. Am I correct?
And if the answer is yes, how do I organize things such that the
Derived delete gets called?
The use case I have is of a single-root hierarchy of heap-allocated
objects handled via smart pointers. The root operator new and delete
is just a general-purpose allocator but each class can have (and it
often does) its own special allocators.
TIA, best regards,
G. Rodrigues