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

时间:2016-07-30 04:03:33

标签: c++

请查看下面的程序代码。我已经提出了很多意见,以明确我遇到问题是什么。

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

1 个答案:

答案 0 :(得分:8)

这条线很奇怪

A& o = *(new A);

考虑改变它。我没有看到只是声明指针A* o = new A();的任何优势。

如果要释放内存:

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

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

A o = *(new A);

你将有 no 解除内存的方式,因为o将是A分配的副本(带有一个全新的地址!)。因此,o将在堆栈上创建,因此delete &o;将导致未定义的行为。