Many libraries like boost use ::new
and ::delete
.
Example from boost::make_shared
template< class T, class... Args > typename boost::detail::sp_if_not_array< T >::type make_shared( Args && ... args ) { boost::shared_ptr< T > pt( static_cast< T* >( 0 ), BOOST_SP_MSD( T ) ); boost::detail::sp_ms_deleter< T > * pd = static_cast<boost::detail::sp_ms_deleter< T > *>( pt._internal_get_untyped_deleter() ); void * pv = pd->address(); ::new( pv ) T( boost::detail::sp_forward<Args>( args )... ); pd->set_initialized(); T * pt2 = static_cast< T* >( pv ); boost::detail::sp_enable_shared_from_this( &pt, pt2, pt2 ); return boost::shared_ptr< T >( pt, pt2 ); }
What does this mean? and why would one use ::new
over just new?
The new operator invokes the function operator new . For arrays of any type, and for objects that aren't class , struct , or union types, a global function, ::operator new , is called to allocate storage. Class-type objects can define their own operator new static member function on a per-class basis.
new creates an instance, whereas new[1] creates a single-element array. new[1] will almost certainly incur (small) memory overhead compared to new to store the size of the array.
The main difference between new and delete operator in C++ is that new is used to allocate memory for an object or an array while, delete is used to deallocate the memory allocated using the new operator. There are two types of memory as static and dynamic memory.
The new and delete operators are designed to support explicitly managed lifetimes. Another common reason is that the size or structure of the "object" is determined at runtime. For simple cases (arrays, etc.)
A class C
could define its own operator new
(this enables, for example, to have your own allocation policy for that class, and/or to provide some Allocator for it. Many standard containers templates accept an optional allocator argument, for example the second argument to std::vector
; see also std::allocator
and this example).
If you code new C
, that operator would be used (if it exists).
If you code ::new C
, the global new
is used
Your example is using the global placement new
new
, new[]
, delete
, and delete[]
(including the placement variants) are overridable both at class
and at global scope, although doing the latter is ill-advised.
When you see ::new
, you are using the global new
operator.
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