请查看下面的程序代码。我已经提出了很多意见,以明确我遇到问题是什么。
#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;
}
答案 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;
将导致未定义的行为。