1

I would like to understand all differences between operator new(std::size_t) and new-expression.

#include <iostream>
#include <new>

using std::cout;

struct A
{
    int a;
    char b;
    A(){ cout << "A\n"; a = 5; b = 'a'; } 
    ~A(){ cout << "~A\n"; }
};

A *a = (A*)operator new(sizeof(A)); //allocates 8 bytes and return void*
A *b = new A(); //allocates 8 bytes, invoke a default constructor and return A*

Could you provide all differences between them? Do they work in a different way?

St.Antario
  • 26,175
  • 41
  • 130
  • 318

2 Answers2

2

The new-expression allocates the memory needed and calls the respective constructor (given the arguments) for the newly allocated object.

The new(std::size_t) operator just allocates the memory.

Read more at http://www.cplusplus.com/reference/new/operator%20new/

ericbn
  • 10,163
  • 3
  • 47
  • 55
1

The new expression invokes the allocation function operator new. The allocation function obtains memory, and the new expression converts memory into objects (by constructing them).

So the following code:

T * p = new T(1, true, 'x');
delete p;

Is equivalent to the following sequence of operations:

void * addr = operator new(sizeof(T));   // allocation

T * p = new (addr) T(1, true, 'x');      // construction

p->~T();                                 // destruction

operator delete(addr);                   // deallocation

Please note that you always need a new expression to create objects (i.e. call constructors) -- constructors have no name and cannot be called directly. In this case, we use the default placement-new expression, which does nothing but create the object, unlike the non-placement form, which does both memory allocation and object construction.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084