Hi everyone.
Reading "The C++ Programming Language", I've read that the basic difference between
new/malloc
and
malloc/delete
is that with the letters we do not invoke constructor/destructor. I know that in C++ I should try to avoid them malloc/free much as possible, but I want to understand in details the difference between
free
and
delete
.
In particular, I want to clearly see the distinction between
free the memory and
call the destructor.
I built the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v)
{
for (auto &x : v)
{
os << x << "\n";
}
return os;
}
int main()
{
{
std::vector<double> *ptv = static_cast<std::vector<double> *>(malloc(sizeof(std::vector<double>))); //24(=3*8) bytes on the heap
ptv = new(ptv) std::vector<double>{};
ptv->push_back(96.5);
ptv->push_back(96.5);
ptv->~vector(); //calling the destructor of the vector pointed to by ptr
std::free(ptv); //free the memory owned by ptv
std::cout << *ptv << std::endl;
}
return 0;
}
| |
Question 1):
- If I comment line 23 but leave uncommented line 22,
24 bytes are lost, because I'm not releasing the raw memory I allocated with
malloc
. Calling the destructor of vector, allows me to clear the content of my vector on the heap
- If I comment line 22 but leave uncommented line 23, the 24 bytes allocated with malloc are released, but the
16 bytes corresponding to 2 doubles on the heap are not released. In practice, the vector has not been destroyed and, indeed, they are printed to the screen.
Are my explanations of those leaks correct?
Question 2): Can we say that free acts on the pointer variable, while the destructor really acts on the object itself (the vector on the heap)?