关于C ++中的新布局 [英] Regarding placement new in C++
问题描述
我在放置新操作符时遇到了问题.我有两个程序:Program1(operator.cpp)和Program2(main.cpp): 程序1:operator.cpp
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;
}
这是第一个链接到的第二个程序: main.cpp:
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);
}
我正在分别编译operator.cpp和main.cpp,如下所示:
I am individually compiling operator.cpp and main.cpp as shown:
operator.cpp: g++ -g -c -o operator operator.cpp
然后将其与main.cpp链接:
Then linking it with main.cpp:
g++ -g -o target operator main.cpp.
令人惊讶的是,当我执行"./target"时,它正在打印:"From normal new". 预期的输出是:从正常新 从新的展示位置开始.
Surprisingly, when i am executing "./target" it is printing: "From normal new". The expected output is: 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.
推荐答案
在您的[main.cpp]中包括了<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.
因此,由new
声明的函数是唯一已知的函数,并且也是被调用的函数.
Hence the function declared by new
is the only one that's known, and the one that's called.
顺便说一句,请注意,C ++ 98§18.4.1.3/1禁止替换上面显示的功能(以及其他三个,即具有void*
位置的new
和delete
的单个对象和数组形式)论点).
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.
干杯hth.,
这篇关于关于C ++中的新布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!