Is there any diference between:

X* x = new X;
	X* y = operator new X;

Recommended Answers

All 3 Replies

Yes -- the first one is well-formed C++ (if X is a type and x isn't already defined in the same scope) and the second isn't.

As arkoenig said, as you have written it, it doesn't compile.

If you are using the construct operator new, you need to do it like this:

class X
{
  X() { std::cout<<"Constructor called "<<std::endl; }
  ~X() { std::cout<<"Destructor called "<<std::endl; }
};

int main() 
{
  X *x=new X;
  X *y= static_cast<X*>(operator new (sizeof(X)));
  delete x;
  delete y;
}

BUT be very careful: the constructor is only called ONCE. ie only for x, not for y. Be very very careful calling it, because if you don't have a POD [plain old data] type class, you are opening yourself to a nightmare of runtime problems.

Putting it differently: If you have to ask about how to use operator new, you shouldn't be using it.

commented: Very true. +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.