※ 引述《ric2k1 (Ric)》之銘言:
Q:
==
我想再請問的是:
A* p = new A ;
cout << p << endl ;
delete p ;
cout << p << endl ;
為何delete掉之後和之前的位址都是一樣的呢?
-------------------------------------------------------------
A:
==
1. delete p 的 prototype 為 void operator delete (void* p),
It is "pass-by-value" (p), and therefore, after the function returns,
the value of the parameter 'p' will not change.
2. p is a local variable to this scope. What the delete operator does is
"release the memory space 'p' points to". p will remain valid within
this scope.
3. "cout << p" prints out the "content" of 'p', which is the memory address.
It is OK to print out an address even if it is no longer valid (i.e. freed).
What is NOT OK is to print out the content of this address, that is,
"cout << *p".
-------------------------------------------------------------
Q:
==
在昨天上課第二堂一開始講的東西我有點不太清楚想問一下
老師有舉個例子
{
A* p= new A;
}
delete p;
[call ]
~A( );
請問一下 這邊想要表達的主旨是什麼
是說離開 { } 後 會自動call delete p and then call destructor ?
還是 說…
還是我還有漏掉什麼? 記得老師是舉兩個來比較
-------------------------------------------------------
A:
==
{
A* p= new A;
}
結束後並不會自動 call "delete p". 只會將 local variable p 還給系統.
如果你要將 p 所指的記憶體空間釋放, 你必須 explicitly 呼叫 "delete p",
然後他才會去呼叫 p 的 destructor ~p().
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.121.134.251
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.121.131.15