Regarding placement new in C++
I am having a problem with the placement new operator. I have two programs: Program1 (operator.cpp) and Program2 (main.cpp):
Program1: operator.cpp
void *operator new(size_t size)
{
void *p;
cout << "From normal new" << endl;
p=malloc(size);
return p;
}
void *operator n开发者_JS百科ew(size_t size, int *p) throw()
{
cout << "From placement new" << endl;
return p;
}
Here is the second program to which the first is linked: main.cpp:
#include <new>
int main()
{
int *ptr=new int;
int *ptr1=new(ptr) int(10);
}
I am individually compiling operator.cpp and main.cpp as shown:
operator.cpp: g++ -g -c -o operator operator.cpp
Then linking it with main.cpp:
g++ -g -o target operator main.cpp.
Surprisingly, when I am executing "./target" it is printing: "From normal new". The expected output is:
From normal new From placement new
However, if the placement new and the main are put in the same file itself, then the output is as expected:
From normal new, From placement new.
In your [main.cpp] you're including <new>
, which declares the function
void* operator new( size_t size, void* p) throw()
You don't declare your own function.
Hence the function declared by new
is the only one that's known, and the one that's called.
By the way, note that C++98 §18.4.1.3/1 prohibits replacement of the function shown above (plus three others, namely single object and array forms of new
and delete
with void*
placement argument).
Also, while I'm on the "by the way" commenting, chances are that whatever placement new is thought to be the solution of, there is probably a safer and just as efficient and more clear higher level solution.
精彩评论