Base * p = new(buf)Base是什么意思?

时间:2015-06-30 16:08:20

标签: c++ valgrind

我最近遇到了一些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;

我在Googling之前和之后都没见过这种语法我不确定在找到解释时会搜索什么。

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

谢谢。

1 个答案:

答案 0 :(得分:2)

它的位置 - 新。它在已分配的内存块上调用构造函数。

通常new执行2个功能:

  • 为对象分配内存

  • 通过初始化将该内存转换为对象

placement-new就是第二位。

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