A question asked in a forum said:
Why
does void* p = new (1024); gives me a compilation error while void* p =
operator new (1024); works. What is the difference between new and
"operator new"?
Lets go back to the
beginning. Once upon a time there was this C language that used 'malloc'
to allocate memory. Then when C++ came, a new way was defined of
allocating memory by the use of 'new'. Its supposed to be much safter
and better way but some software gurus may differ. Memory for 'new' is
allocated from 'Free Store' and memory by 'malloc' is generated from
'heap'. The 'heap' and 'Free Store' may be the same area and is a
compiler implementation detail.
The syntax for 'operator new' is:
void* new (std::size_t size);
All it does is allocate a memory of size specified
On the other hand, 'new' does 2 things:
1. It calls 'operator new'
2. It calls constructor for the type of object
In the above case since 1024 is not a type, it will fail in calling its constructor.
'new' is also referred to as 'keyword new' or 'new operator' to cause more confusion :)
Here
is a small example to play with 'operator new' after the example you
will realise that regardless of what is passed, it always allocates a 4
byte memory.
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy#include<iostream> using namespace std; int main() { //void* p = new (1024); void* p = operator new (1024); //Lets test if we can do anything with the memory cout<<"p = "<<p<<endl; cout<<"sizeof(p) = "<<sizeof(p)<<endl; int *x = static_cast<int *>(p); cout<<"*x before = "<<*x<<endl; *x = 23456; cout<<"*x after = "<<*x<<endl; void* q = operator new (0); cout<<"\nq = "<<q<<endl; cout<<"sizeof(q) = "<<sizeof(q)<<endl; x = static_cast<int *>(q); cout<<"*x before = "<<*x<<endl; *x = 65432; cout<<"*x after = "<<*x<<endl; void* z = operator new ('a'); cout<<"\nz = "<<z<<endl; cout<<"sizeof(z) = "<<sizeof(z)<<endl; x = static_cast<int *>(z); cout<<"*x before = "<<*x<<endl; *x = 11111; cout<<"*x after = "<<*x<<endl; return 0; }
The output is as follows:
No comments:
Post a Comment