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;'로'new'를 피하십시오. – Jarod42