📅 2010-Nov-05 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, new ⬩ 📚 Archive
In C++, the new expression is used to create an object on the heap. For example:
class Foo
{public:
Foo()
{"Constructor";
cout <<
}
};
int main()
{new Foo(); // new
Foo* f = return 0;
}
What actually happens when a new expression new Foo()
is executed is:
The default operator new
function is called. This function merely allocates enough memory to hold an object of Foo
. It returns a void*
pointer to this memory.
The constructor of Foo
is called to initialize the object memory obtained from the above step.
The confusing part here is the difference between the new expression and the operator new function. The new expression is a part of the language, it cannot be modified. It behaves as described above.
The operator new has a default implementation in the standard library. But, it can also be overloaded for a class. For example:
#include <iostream>
using namespace std;
class Foo
{public:
Foo()
{"Foo constructor" << endl;
cout <<
}
void* operator new( size_t i )
{"operator new" << endl;
cout << return malloc( i * sizeof( Foo ) ); // Allocate raw memory
}
};
int main()
{new Foo();
Foo* f = return 0;
}
Executing the new expression new Foo()
first results in a call to Foo::operator new()
and consequently to the Foo constructor. The operator new function has a fixed function signature. The first parameter is always a size_t
and it returns a void*
pointer to the allocated memory. Overloading the operator new function is how a custom allocator is provided for a class.