2016-07-30 62 views
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; 
} 
+1

只要避免'新'與'A o;'。 – Jarod42

回答

9

此行是怪異

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;會導致未定義的行爲。