Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between new and ::new

Tags:

c++

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?

like image 847
tejas Avatar asked Feb 22 '18 13:02

tejas


People also ask

What is :: operator 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.

What is the difference between new [] and new () in SV?

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.

What is difference between new and delete operators?

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.

Why use new and delete?

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.)


2 Answers

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

like image 90
Basile Starynkevitch Avatar answered Sep 21 '22 12:09

Basile Starynkevitch


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.

like image 40
Bathsheba Avatar answered Sep 18 '22 12:09

Bathsheba