I have been told that "new-expression will call operator new
to manage dynamic storage and initialize the object at the same time" many times. And I don't doubt about that. But I'm wondering that since operator new
is declared in standard library header <new>
, how could we still using new-expression even if we include no header files.
Is operator new
a part of C++ core language or the compiler includes <new>
implicitly?
Yes operator new
is part of the standard. The implementation is required to supply the operator at the global scope in each translation unit in your program. From [basic.stc.dynamic]/2
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.4.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); void* operator new[](std::size_t); void operator delete(void*); void operator delete[](void*); void operator delete(void*, std::size_t) noexcept; void operator delete[](void*, std::size_t) noexcept;
emphasis mine
This is why you do not need to include anything to use new
/new[]
and delete
/delete[]
.
Yes, operator new
is part of the C++ standard.
See [expr.new].
Most of #include <new>
is implicitly declared. But #include <new>
declares some more versions of operator new
, which are not implicit, for example placement new*:
void* operator new (std::size_t size, void* ptr) noexcept;
void* operator new[](std::size_t size, void* ptr) noexcept;
* placement new is not recommended for daily use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With