【发布时间】:2011-02-16 19:39:47
【问题描述】:
根据this reference为operator new:
全局动态存储运算符 功能在标准中是特殊的 图书馆:
- operator new 的所有三个版本都在全局命名空间中声明, 不在 std 命名空间中。
- 第一个和第二个版本在每个 C++ 程序的翻译单元: 标题不需要是 包括在内,以便他们在场。
在我看来,这似乎暗示 operator new 的第三个版本(位置 new)并未在 C++ 程序的每个翻译单元中隐式声明,并且确实需要包含标头 <new>展示。对吗?
如果是这样,如何使用 g++ 和 MS VC++ Express 编译器,我似乎可以在源代码中不使用 #include <new> 的第三版 new 编译代码?
此外,operator new 上的 MSDN 标准 C++ 库参考条目为 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> 的情况下将无法编译?
【问题讨论】:
标签: c++ new-operator include standard-library