Search code examples
c++pointersnew-operator

Why are there so many different ways to use new operator in C++


I've just read the new operator explanation on the cplusplus.com. The page gives an example to demonstrate four different ways of using new operator as following:

// operator new example
#include <iostream>
#include <new>
using namespace std;

struct myclass {myclass() {cout <<"myclass constructed\n";}};

int main () {

   int * p1 = new int;
// same as:
// int * p1 = (int*) operator new (sizeof(int));

   int * p2 = new (nothrow) int;
// same as:
// int * p2 = (int*) operator new (sizeof(int),nothrow);

   myclass * p3 = (myclass*) operator new (sizeof(myclass));
// (!) not the same as:
// myclass * p3 = new myclass;
// (constructor not called by function call, even for non-POD types)

   new (p3) myclass;   // calls constructor
// same as:
// operator new (sizeof(myclass),p3)

   return 0;
}

My questions are:

  1. What is the best practice of using new operator?
  2. Is myclass* p3 = new myclass equivalent to myclass* p3 = new myclass()?

Solution

  • Because they have different purposes. If you didn't want new to throw std::bad_alloc on failure, you would use nothrow. If you wanted to allocate your objects in existing storage, you would use placement new … if you want raw, uninitialized memory, you would invoke operator new directly and cast the result to the target type.

    The plain standard usage of new in 99% of all cases is MyClass* c = new MyClass();

    To your second question: the new Object() vs. new Object forms are not generally equal. See this question and the responses for the details. But that really is nitpicking. Usually they are equivalent, but to be on the safe side always pick new Object(); Note that, in this particular sample they are equal because MyClass doesn't have any members, so strictly speaking the answer to your question is yes.