1
請看下面的程序代碼。我已經提出了很多意見,以說明我遇到了什麼問題。我們如何取消分配像這樣分配的內存:A&o = *(new A)?
#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;'。 – Jarod42