0
template <class _T1>
inline void constructInPlace(_T1 *_Ptr)
{
    new (static_cast<void*>(_Ptr)) _T1();
}

I have known the place new about c++, I can't understand the above syntax!

David G
  • 94,763
  • 41
  • 167
  • 253
paul08colin
  • 51
  • 1
  • 7

1 Answers1

2

This syntax is known as placement new. It lets you construct objects in memory locations that you already own. It does NOT allocate memory for you.

In this case, a T1 object is being constructed in the memory location pointed to by _Ptr, since new expects void*, it is being cast down. The cast would happen implicitly anyway, looks like the explicit cast is to make the intent clear.

Community
  • 1
  • 1
Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • oh,I have discover the new operator ( inline void* operator new(std::size_t, void* __p) throw() { return __p; }) but why expects void*? – paul08colin Jan 10 '13 at 01:35
  • When a memory location is just that a memory location and has no semantics about what it contains, it is typically expressed as `void *`because it can contain anything, and does contain nothing – Karthik T Jan 10 '13 at 01:38
  • A typed pointer can be assigned to a void* pointer without using a type-cast, eg: `new (_Ptr) _T1();` – Remy Lebeau Jan 10 '13 at 01:41
  • It would be implicitly cast down anyway right. Perhaps this was just to make the intent clear. – Karthik T Jan 10 '13 at 01:42