I am curious how the delete operator know the size of the derived class when calling delete on base pointer, here is a minimal example:
class IVariant
{
public:
virtual ~IVariant() = default;
virtual void print_value() = 0;
};
template<typename T>
class Variant: public IVariant {};
template<>
class Variant<int>: public IVariant
{
private:
int m_integer;
public:
Variant(int integer): m_integer(integer) {}
void print_value() override
{
printf("integer: %i\n", m_integer);
}
};
template<>
class Variant<double>: public IVariant
{
private:
double m_dbl;
public:
Variant(double val): m_dbl(val) {}
void print_value() override
{
printf("double: %g\n", m_dbl);
}
};
template<>
class Variant<std::string>: public IVariant
{
private:
std::string m_string;
public:
Variant(const std::string& string): m_string(string) {}
void print_value() override
{
printf("string: %s\n", m_string.c_str());
}
};
Test:
int main()
{
IVariant* int_var = new Variant<int>(100);
IVariant* dbl_var = new Variant<double>(100.0f);
IVariant* str_var = new Variant<std::string>("the value is 100\n");
int_var->print_value();
dbl_var->print_value();
str_var->print_value();
delete int_var;
delete dbl_var;
delete str_var;
}
The delete operator correctly knew from the base pointer alone that int_var = variant<int>
so freed 4 bytes, dbl_var = variant<double>
so freed 8 bytes, str_var = variant<std::string>
so it freed 28 bytes.
But how does it know? Does the new operator store size & pointer which the delete operator can then use to free the correct number of bytes? I know this is how delete[] works for arrays but I was unable to find any info when it came to derived classes
delete
and delete[]
operators know the size of the allocation, because operators new
and new[]
save some housekeeping information for them at the time of allocation. It uses the same idea as malloc
/free
pair, when malloc
saves size information that is required for free
to do its job.
Figuring out the allocation size is independent of the type for which the memory is allocated. Operators delete
and delete[]
do not even know the type of the pointer being deleted, because they operate on void
pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With