这种使用放置 new[] 有什么问题?做

What's wrong with this use of placement new[]? do

本文关键字:什么 问题 new      更新时间:2023-10-16

考虑下面的程序。它是由一个复杂的情况简化而来的。它在删除以前分配的内存时失败,除非我删除Obj类中的虚拟析构函数。我不明白为什么程序输出的两个地址不同,除非存在虚析构函数。

// GCC 4.4
#include <iostream>
using namespace std;
class Arena {
public:
    void* alloc(size_t s) {
        char* p = new char[s];
        cout << "Allocated memory address starts at: " << (void*)p << 'n';
        return p;
    }
    void free(void* p) {
        cout << "The memory to be deallocated starts at: " << p << 'n';
        delete [] static_cast<char*> (p); // the program fails here
    }
};
struct Obj {
    void* operator new[](size_t s, Arena& a) {
        return a.alloc(s);
    }
    virtual ~Obj() {} // if I remove this everything works as expected
    void destroy(size_t n, Arena* a) {
        for (size_t i = 0; i < n; i++)
            this[n - i - 1].~Obj();
        if (a)
            a->free(this);
    }
};

int main(int argc, char** argv) {
    Arena a;
    Obj* p = new(a) Obj[5]();
    p->destroy(5, &a);
    return 0;
}

这是我的实现中存在虚析构函数时程序的输出:

分配的内存地址从:0x8895008开始要释放的内存从以下位置开始:0x889500c

RUN FAILED (exit value 1)

请不要问程序应该做什么。正如我所说,它来自一个更复杂的情况,Arena是各种类型内存的接口。在这个例子中,内存只是从堆中分配和释放。

this不是newchar* p = new char[s];行返回的指针,可以看到这里的s的大小大于5个Obj实例。差异(应该是sizeof (std::size_t))在额外的内存中,包含数组的长度5,紧接this中包含的地址。

http://sourcery.mentor.com/public/cxx-abi/abi.html array-cookies

2.7 Array Operator new Cookies

当使用new操作符创建新数组时,通常存储cookie以记住分配的长度(数组元素的数量),以便可以正确地释放。

专:

如果数组元素类型T有一个普通的析构函数(12.4 [class.dtor])和通常的(array)释放函数(3.7.3.2 [basic.stc.dynamic.deallocation])函数不接受两个参数,则不需要cookie。

因此,析构函数的性是无关紧要的,重要的是析构函数是非平凡的,您可以通过删除析构函数前面的关键字virtual来轻松检查,并观察程序崩溃。

根据chills的回答,如果你想让它"安全":

#include <type_traits>
a->free(this - (std::has_trivial_destructor<Obj>::value ? 1 : 0));