我们如何释放这样分配的内存:A&o=*(新A)

How do we deallocate memory that has been allocated like this: A& o = *(new A)?

本文关键字:amp 何释放 释放 我们 分配 内存      更新时间:2023-10-16

请看下面的程序代码。我已经发表了很多评论,以明确我的问题所在。

#include <iostream>
class A {
    public:
        void test() {
            std::cout << "foo" << std::endl;
        }
};
int main() {
    A& o = *(new A); // The memory for object "o" is allocated on the heap.
    o.test();        // This prints out the string "foo" on the screen.
                     // So far so good.
    // But how do I now deallocate the memory used by "o"? Obviously,
    // memory has been allocated, but I know of no way to relinquish it
    // back to the operating system.
    // delete o;     // Error: type ‘class A’ argument given to ‘delete’,
                     // expected pointer

    return 0;
}

这行很奇怪

A& o = *(new A);

考虑更改它。我认为仅仅将它声明为指针A* o = new A();没有任何好处。


如果您想取消分配内存:

delete &o; //Deletes the memory of 'o'

请注意,如果您已将o定义为

A o = *(new A);

您将没有释放内存的方式,因为o将是分配的A的副本(具有全新的地址!)。o将因此在堆栈上创建,因此delete &o;将导致未定义的行为。