c++ - placement new 如何在指定内存上构造对象
PHPz
PHPz 2017-04-17 15:21:05
0
2
594
// 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上完成构造的呢?明明只是把指针返回了啊。

PHPz
PHPz

学习是最好的投资!

reply all(2)
伊谢尔伦

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.

大家讲道理

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template