Osama Ahmad
Osama Ahmad

Reputation: 2096

What makes placement new call the constructor of an object?

From here:

The Standard C++ Library provides a placement form of operator new declared in the standard header as:

void *operator new(std::size_t, void *p) throw ();

Most C++ implementations define it as an inline function:

inline
void *operator new(std::size_t, void *p) throw () 
{
    return p;
}

It does nothing but return the value of its second parameter. It completely ignores its first parameter. The exception-specification throw () indicates that the function isn't allowed to propagate any exceptions.

I know that placement new is just an overload to operator new, also that it calls the constructor on a given memory address.

But what makes it call the constructor? It just takes a pointer and returns it again. what's the point of taking a pointer then returning it? why pass a value to a function to take it back?

Upvotes: 0

Views: 380

Answers (1)

But what makes it call the constructor?

The semantics of operator new

For details, read the C++11 standard n3337 about new expressions, or a newer variant of that standard.

When you define some operator new, using it later would call the constructor. By definition of C++.

I recommend reading a good C++ programming book.

Exercise: define the usual operator new (in your class MyClass) using malloc, the placement new, and some throw expression.

Upvotes: 3

Related Questions