Base*p=new(buf)Base;的含义是什么;

What is the meaning of Base* p = new(buf) Base;

本文关键字:Base 是什么 buf new      更新时间:2023-10-16

我最近遇到了一些C++代码,它应该说明valgrind、gdb、insure等中可能出现的许多不同类型的错误。。。

其中一个例子如下:

// =============================================================================
// A base class without a virtual destructor
class Base
{
    public:
        ~Base() { std::cout << "Base" << std::endl; }
};
// Derived should not be deleted through Base*
class Derived : public Base
{
    public:
        ~Derived() { std::cout << "Derived" << std::endl; }
};
// A class that isn't Base
class NotBase
{
    public:
        ~NotBase() { std::cout << "NotBase" << std::endl; }
};
// =============================================================================
// Wrong delete is called. Should call ~Base, then
// delete[] buf
void placement_new()
{
    char* buf = new char[sizeof(Base)];
    Base* p = new(buf) Base;
    delete p;
}

我的问题与以下行有关:

Base* p = new(buf) Base;

我以前从未见过这种语法,在谷歌上搜索了很多次之后,我甚至不知道该搜索什么来找到解释。

有人能给我指正确的方向吗?如果这是多余的或简单的,我深表歉意,但我很好奇这个例子中发生了什么。

谢谢。

这是一个新的布局。它在已经分配的内存上调用构造函数。

通常新的执行2个功能:

  • 为对象分配内存

  • 通过初始化将内存变成一个对象

placementnew只起到了第二个作用。

它在stl分配器实现中使用了很多。