简体   繁体   中英

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?

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 someoperator 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM