auto_ptr的一個簡單例子

c++中申請指針通常採用的方式是new和delete。然而標準c++中還有一個強大的模版類就是auto_ptr,它可以在你不用的時候自動幫你釋放內存。下面簡單說一下用法。

用法一

std::auto_ptr<MyClass>m_example(new MyClass());

用法二

std::auto_ptr<MyClass>m_example;

m_example.reset(new MyClass());

用法三(指針的賦值操作)

std::auto_ptr<MyClass>m_example1(new MyClass());

std::auto_ptr<MyClass>m_example2(new MyClass());

m_example2=m_example1;

則c++會把m_example所指向的內存回收,使m_example 的值爲null,所以在c++中,應絕對避免把auto_ptr放到容器中。即應避免下列代碼

vector<auto_ptr<MyClass>>m_example;

當用算法對容器操作的時候,你很難避免stl內部對容器中的元素實現賦值傳遞,這樣便會使容器中多個元素被置位null,而這不是我們想看到的。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章