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

发布于 2024-12-18 01:52:42 字数 1266 浏览 2 评论 0原文

考虑下面的程序。它是由一个复杂的案例简化而来的。除非我删除 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

运行失败(退出值 1)

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

Consider the program below. It has been simplified from a complex case. It fails on deleting the previous allocated memory, unless I remove the virtual destructor in the Obj class. I don't understand why the two addresses from the output of the program differ, only if the virtual destructor is present.

// 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;
}

This is the output of the program in my implementation when the virtual destructor is present:

Allocated memory address starts at: 0x8895008
The memory to be deallocated starts at: 0x889500c

RUN FAILED (exit value 1)

Please don't ask what the program it's supposed to do. As I said it comes from a more complex case where Arena is an interface for various types of memory. In this example the memory is just allocated and deallocated from the heap.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

计㈡愣 2024-12-25 01:52:43

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

好的,规范说得很清楚:

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

2.7 数组运算符新 Cookie

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

具体:

<块引用>

如果数组元素类型 T 有一个简单的析构函数 (12.4 [class.dtor]) 并且通常的(数组)释放函数 (3.7.3.2 [basic.stc.dynamic.deallocation]) 函数没有,则不需要 cookie采用两个参数。

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

this is not the pointer returned by the new at line char* p = new char[s]; You can see that the size s there is bigger than 5 Obj instances. The difference (which should be sizeof (std::size_t)) is in additional memory, containing the length of the array, 5, immediately before the address contained in this.

OK, the spec makes it clear:

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

2.7 Array Operator new Cookies

When operator new is used to create a new array, a cookie is usually stored to remember the allocated length (number of array elements) so that it can be deallocated correctly.

Specifically:

No cookie is required if the array element type T has a trivial destructor (12.4 [class.dtor]) and the usual (array) deallocation function (3.7.3.2 [basic.stc.dynamic.deallocation]) function does not take two arguments.

So, the virtual-ness of the destructor is irrelevant, what matters is that the destructor is non-trivial, which you can easily check, by deleting the keyword virtual in front of the destructor and observe the program crashing.

醉生梦死 2024-12-25 01:52:43

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

#include <type_traits>

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

Based on chills' answer, if you want to make it "safe":

#include <type_traits>

a->free(this - (std::has_trivial_destructor<Obj>::value ? 1 : 0));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文