作者ric2k1 (Ric)
看板EE_DSnP
标题Re: [Q&A] Memory management (lecture 12/01/2006)
时间Mon Dec 4 10:00:19 2006
※ 引述《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