c++ - 我们如何释放已分配的内存 : A& o = *(new A)?

标签 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;
}

最佳答案

这条线很奇怪

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;会导致未定义的行为。

关于c++ - 我们如何释放已分配的内存 : A& o = *(new A)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38670228/

相关文章:

c++ - 以下 C++ 代码是否等价? (在智能指针实现中)

c++ - 如何在 C++11 的迭代器中获取有关 auto 标识符的更多详细信息

c++ - 如何在没有默认构造函数的情况下在另一个类中创建模板类

c++ - boost iOS 链接错误

c++ - 为什么 C++ 字符串需要 a\0?

c++ - 使用 Boost 预处理器解析元素序列

c++ - 如何在 C++ 中仅包含头文件中的一个符号

c++ - std::unordered_map 的哈希值

c++ - BGL depth_first_search 颜色图错误

c++ - Linux 到 Windows C++ 端口