请看下面的程序代码。我已经发表了很多评论来阐明我遇到的问题。
#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/