Re: What are the key differences between operator new and operator
new[]?
On Feb 3, 8:57 pm, "Fred Zwarts" <F.Zwa...@KVI.nl> wrote:
"xmllmx" <xml...@gmail.com> wrote in message
news:26104060-3bf4-4be0-b207-e39b4b0f1187@b36g2000pri.googlegroups.com
Dear all,
As we know, the C++ standard defines at least four special global
functions as follows:
1) void* operator new(size_t);
2) void* operator new[](size_t);
3) void operator delete(void*);
4) void operator delete[](void*);
In Visual C++, 2) and 4) simply forward their respective call to 1)
and 3). Obviously, 1) and 3) are equivalents respectively to malloc
and free in C.
However, when and why should we call 2) and 4)?
Normally, you don't call these operators explicitly, but you use
new and new [] to create new objects and delete and delete [] to
destroy objects. In these cases there is much more than just malloc
and free. In addition to allocating memory, new and new [] call
constructors to create objects and in addtion to freeing memory,
delete and delete[] call destructors to destroy objects.
2) and 4) should be used for arrays. They call the constructors,
resp. destructors for all array elements, whereas new and delete
call only one constructor, resp. destructor.
Though 2) and 4) are not harmful, but I think them rather ugly.
Because I can not find any necessity of them.
That is probabbly, because you think they only allocate/free memory,
but they are used for many more functionality.
I hope someone can give me a convincing explanation? Thanks in
advance!
I hope this is convincing.
Many thanks to your quick response.
I think you may misunderstand what I mean. I fully know the difference
between malloc/free and new/delete. I don't know if you know the fact:
1) operator new(size_t); totally differs from a new expression. Let me
illustrate that in source code:
struct CTest
{
CTest()
{
std::cout << "Call CTest::ctor();" << std::endl;
}
~CTest()
{
std::cout << "Call CTest::dtor(); " << std::endl;
}
};
int main()
{
CTest* p = new CTest; // 1)
delete p; // 2)
void* p2 = operator new(sizeof(CTest)); // 3)
operator delete(p2); // 4)
return 0;
}
The statements 1) and 2) will implicitly call the constructor and
destructor of CTest. However, statements 3) and 4) will never
implicitly call any other member functions of CTest. 3) is totally
equal to void* p2 = malloc(sizeof(CTest)); and 4) to free(p2);