search

Home  >  Q&A  >  body text

c++ - placement new 如何在指定内存上构造对象

// Default placement versions of operator new.
inline void* operator new(std::size_t, void* __p) _GLIBCXX_USE_NOEXCEPT
{ return __p; }
inline void* operator new[](std::size_t, void* __p) _GLIBCXX_USE_NOEXCEPT
{ return __p; }

如上,查看gcc中stl的源代码的实现方式。placement new 只是返回__p指针。若

class XX
{
    //define ctor,dctor here
    //data member
};
char buf[sizeof(XX)];
XX* ptr = new(buf) XX();

像上面这样使用placement new,请问XX是如何在那个指定的内存buf上完成构造的呢?明明只是把指针返回了啊。

PHPzPHPz2813 days ago597

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 15:23:05

    First of all, the placement new you are calling here is not the placement new defined in the header file new. You have to write::operator new(...);.

    Then regarding this placement new, the C++ standard has the following statement (C++11):
    18.6.1.3 Placement forms [new.delete.placement]
    1 These functions are reserved, a C++ program may not define functions that displace the versions in the Standard C++ library (17.6.4). The provisions of (3.7.4) do not apply to these reserved placement forms of operator new and operator delete.

    The general idea is that these functions are reserved there and cannot be moved. They are of no use at the moment.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 15:23:05

    Consider how to initialize the structure.
    As long as the memory is allocated, you can reinterpret_cast this memory into the type you want. This process allows the member variables of the class to have their own memory space, and then call the constructor of this type. This is the principle. You can also manually implement a placement new

    reply
    0
  • Cancelreply