Regarding placement new in C++

孤人 提交于 2019-12-08 08:24:23

问题


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 new(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

Can anyone please help me regarding this? This stuff is related to my official work and is very very urgent.


回答1:


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.

Cheers & hth.,



来源:https://stackoverflow.com/questions/4688401/regarding-placement-new-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!