Search code examples
c++new-operatorincludestandard-library

When is #include <new> library required in C++?


According to this reference for operator new:

Global dynamic storage operator functions are special in the standard library:

  • All three versions of operator new are declared in the global namespace, not in the std namespace.
  • The first and second versions are implicitly declared in every translation unit of a C++ program: The header does not need to be included for them to be present.

This seems to me to imply that the third version of operator new (placement new) is not implicitly declared in every translation unit of a C++ program and the header <new> does need to be included for it to be present. Is that correct?

If so, how is it that using both g++ and MS VC++ Express compilers it seems I can compile code using the third version of new without #include <new> in my source code?

Also, the MSDN Standard C++ Library reference entry on operator new gives some example code for the three forms of operator new which contains the #include <new> statement, however the example seems to compile and run just the same for me without this include?

// 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;
}

Could anyone shed some light on this, and when and why you might need to #include <new> - maybe some example code that will not compile without #include <new>?


Solution

  • Nothing in C++ prevents standard headers from including other standard headers. So if you include any standard header you might conceivably indirectly include all of them. However, this behaviour is totally implementation dependent, and if you need the features of a specific header you should always explicitly include it yourself.