根据此参考:operator new
全局动态存储操作符函数在标准库中是特殊的:
- 所有三个版本的 operator new 都在全局命名空间中声明,而不是在 std 命名空间中。
- 第一个和第二个版本在 C++ 程序的每个翻译单元中隐式声明:不需要包含头文件就可以显示它们。
在我看来,这似乎暗示operator new
(placement new
) 的第三个版本并未在 C++ 程序的每个翻译单元中隐式声明,并且<new>
确实需要包含标头才能使其存在。那是对的吗?
如果是这样,如何同时使用 g++ 和 MS VC++ Express 编译器,我似乎可以在源代码中使用第三版new
without编译#include <new>
代码?
此外,MSDN 标准 C++ 库参考条目上提供了包含语句operator new
的三种形式的一些示例代码,但是如果没有这个包含,该示例对我来说似乎编译和运行相同?operator new
#include <new>
// new_op_new.cpp
// compile with: /EHsc
#include<new>
#include<iostream>
using namespace std;
class MyClass
{
public:
MyClass( )
{
cout << "Construction MyClass." << this << endl;
};
~MyClass( )
{
imember = 0; cout << "Destructing MyClass." << this << endl;
};
int imember;
};
int main( )
{
// The first form of new delete
MyClass* fPtr = new MyClass;
delete fPtr;
// The second form of new delete
char x[sizeof( MyClass )];
MyClass* fPtr2 = new( &x[0] ) MyClass;
fPtr2 -> ~MyClass();
cout << "The address of x[0] is : " << ( void* )&x[0] << endl;
// The third form of new delete
MyClass* fPtr3 = new( nothrow ) MyClass;
delete fPtr3;
}
任何人都可以对此有所了解,以及何时以及为什么需要#include <new>
- 也许一些示例代码将无法编译#include <new>
?