Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
from:malloc() and free() Versus new and delete
Last updated Apr 21, 2004.
C++ still supports the C library functions malloc() and free(). This backward compatibility with C is useful in three cases:
Combining original C legacy code with C++ programs
Writing C++ code that's meant to be supported in C environments
Implementing or overriding new and delete by calling malloc() and free()
Otherwise, malloc() and free() are not to be used in C++ code because they don't support object semantics. Furthermore, the results of calling free() to release an object that was allocated by new, or of using delete to release memory that was allocated by malloc(), are undefined. The C++ standard doesn't guarantee that the underlying implementation of operator new uses malloc(); in fact, on some implementations malloc() and new use different heaps.
#include <iostream>
using std::cout;
using std::endl;
int ctor_count = 0;
int dtor_count = 0;
// simple class, just to count things happening
class moo {
public:
moo(void);
~moo(void);
};
moo::moo ( void ) {
ctor_count++;
}
moo::~moo ( void ) {
dtor_count++;
}
int main ( ) {
ctor_count = dtor_count = 0;
moo *bar = new moo[5];
cout << "Using New : Constructed = " << ctor_count
<< " Destructed = " << dtor_count << endl;
delete [] bar;
cout << "Using Delete: Constructed = " << ctor_count
<< " Destructed = " << dtor_count << endl;
ctor_count = dtor_count = 0;
// casting is necessary for the return result of malloc
// and constructors / destructors are NOT called
moo *foo = (moo*)malloc( 5 * sizeof *foo );
cout << "Using Malloc: Constructed = " << ctor_count
<< " Destructed = " << dtor_count << endl;
free( foo );
cout << "Using free : Constructed = " << ctor_count
<< " Destructed = " << dtor_count << endl;
}
vector<float> r;