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

4

51

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>?

Milligan answered 7/5, 2010 at 12:9 Comment(0)
S
19

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.

Sunken answered 7/5, 2010 at 12:32 Comment(4)
So, with the code and the compilers I have tried (see original question), the most likely explanation for it compiling ok without the include <new> is that other headers I have included have themselves included the <new> library? If I am understanding your answer correctly then that would resolve my confusion and seems plausible.Milligan
~Czarak Yup. For example, in the GCC implementation I use the header <functional> includes <new> - there may be others.Sunken
Thanks Neil, very concise answer to my central question.Milligan
−1 This does not answer the question in the title, “When is #include <new> library required in C++?”. I guess that that would be OK with the OP. But it's problem when this question is used as referent for a close-as-duplicate of some other question.Boyett
M
16

The C++ Standard verse 3.7.4.2 says :-

The library provides default definitions for the global allocation and deallocation functions. Some global allocation and deallocation functions are replaceable (18.6.1). A C++ program shall provide at most one definition of a replaceable allocation or deallocation function. Any such function definition replaces the default version provided in the library (17.6.3.6). The following allocation and deallocation functions (18.6) are implicitly declared in global scope in each translation unit of a program.

void* operator new(std::size_t) throw(std::bad_alloc); 
void* operator new[](std::size_t) throw std::bad_alloc); 
void operator delete(void*) throw(); 
void operator delete[](void*) throw();

These implicit declarations introduce only the function names operator new, operator new[], operator delete, operator delete[]. [ Note: the implicit declarations do not introduce the names std, std::bad_alloc, and std::size_t, or any other names that the library uses to declare these names. Thus, a new-expression, delete-expression or function call that refers to one of these functions without including the header <new> is well-formed. However, referring to std, std::bad_alloc, and std::size_t is ill-formed unless the name has been declared by including the appropriate header. —end note]

Also, the std::nothrow version of the operator new requires the inclusion of the header (example).

The standard though does not specify implicit inclusion of the header files within other header files. So it is safe and portable to follow the standard when the names std::bad_alloc etc are referred.

Monkeypot answered 7/5, 2010 at 12:35 Comment(2)
Thank you for your answer - I follow everything except the final two sentences of your answer - could you elaborate or clarify?Milligan
@Czarak: It means; if you want your code to be portable, do not rely on implicit header includes of your implementation. Check with reliable sources (like the Standard) for the exact header that declares the functions. the gist is: If atall you need to catch your memory failure errors, you need to include <new> because both std::bad_alloc and std::nothrow are defined there!Monkeypot
B
6

Regarding the question in the title,

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

The keyword new can be used in various ways. Ordinary use does not require inclusion of any headers. But one possible way to use this keyword is to invoke the particular “placement new” function defined by the <new> header. With that usage you need to directly or indirectly include the <new> header. Do not include that header, or any other header, unless you need it; do not include headers by default. On the other hand, do not rely on an implementation specific version of a header including another one: always include what you need as per the standard's (or other) specifications of what they provide.

Regarding the question in the body,

the example seems to compile and run just the same for me without this include?

In C++ standard library headers are permitted to include other standard library headers (or the stuff provided by other standard library headers), at the implementation's discretion.

Boyett answered 26/1, 2017 at 19:5 Comment(0)
A
4

Operator new defined in <new> header throws bad_alloc exception (which is declared in the same header) instead of returning NULL when memory allocation is not possible. <new> header also defines

void* operator new (std::size_t size, const std::nothrow_t& nothrow_constant) throw();

variant which does not throw exceptions and placement new variant. Without <new> you get only plain old, NULL-returning operator new. All three operator overloads:

void* operator new (std::size_t size) throw (std::bad_alloc);
void* operator new (std::size_t size, const std::nothrow_t& nothrow_constant) throw();
void* operator new (std::size_t size, void* ptr) throw();

are declared in <new> header. However, some compilers may make them available implicitly, but this is non-standard, and you should not rely on it.

Alvar answered 7/5, 2010 at 12:20 Comment(5)
It's the other way around. The throwing new is the default, nothrow requires including <new>.Averil
I think that it is the reverse. If you don't include <new>, you get the exception version of new (which is the default, according to the standard). You do not need the declaration of std::bad_alloc to call new, only if you want to catch the exception. If you want the nothrow version, you should include <new>, since std::nothrow is defined in that header.Hypocrisy
It turns out you're right. But, how did it work when C++ didn't have exceptions?Nashbar
@Hypocrisy weird default choice, so what if I want the throw version, so not include <new> but it gets included inadvertently via some other include?Taphouse
also it seems std::bad_array_new_length requires us to include <new>Taphouse

© 2022 - 2024 — McMap. All rights reserved.