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:
- What is the best practice of using
new operator? - Is
myclass* p3 = new myclassequivalent tomyclass* p3 = new myclass()?
Because they have different purposes. If you didn’t want
newto throwstd::bad_allocon failure, you would usenothrow. If you wanted to allocate your objects in existing storage, you would use placement new … if you want raw, uninitialized memory, you would invokeoperator newdirectly and cast the result to the target type.The plain standard usage of
newin 99% of all cases isMyClass* c = new MyClass();To your second question: the
new Object()vs.new Objectforms 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 picknew Object(); Note that, in this particular sample they are equal becauseMyClassdoesn’t have any members, so strictly speaking the answer to your question is yes.