是objPtr
包含指向有效內存的指針。
將元素插入到std::list
中時,list
將其複製一份。在你的情況下,元素是一個地址(一個指針),所以列表會複製地址並存儲它。現在
object * optr = queue->pop_front();
OPTR指向的對象
queue->pop_front();
將刪除list
所述元件(地址/指針),optr
已指向到對象。
完成對象後,請不要忘記刪除它,否則最終會導致內存泄漏。
實施例:
#include <iostream>
#include <list>
using namespace std;
struct A
{
static int count;
A() : val(count++) { cout << "A(" << val << ")" << endl; }
~A() { cout << "~A(" << val << ")" << endl; }
int val;
};
int A::count = 0;
ostream& operator<<(ostream& os, A& a) { return os << a.val; }
int main()
{
list<A*> alist;
for (unsigned int i = 3; i; --i) alist.push_back(new A());
for (unsigned int i = 3; i; --i)
{
A * aptr = alist.front();
alist.pop_front();
cout << *aptr << endl;
delete aptr;
aptr = 0;
}
}
爲什麼這是低票? – sbi 2009-10-14 13:04:11
我沒有downvote,但這裏是我的觀點:你不能簡單地從原生指針切換到shared_ptr,所以這個答案不是很有用。 – foraidt 2009-10-14 13:34:48
爲什麼當你不完全瞭解需求時使用shared_ptr會更好。 – VNarasimhaM 2009-10-14 13:35:51