?? exa_5786.htm
字號:
<HTML><HEAD><TITLE>19.3 Example Program</TITLE></HEAD><BODY><A HREF="ug1.htm"><IMG SRC="images/banner.gif"></A><BR><A HREF="dec_3723.htm"><IMG SRC="images/prev.gif"></A><A HREF="booktoc1.htm"><IMG SRC="images/toc.gif"></A><A HREF="tindex1.htm"><IMG SRC="images/tindex.gif"></A><A HREF="com_8038.htm"><IMG SRC="images/next.gif"></A><BR><STRONG>Click on the banner to return to the user guide home page.</STRONG><H2>19.3 Example Program</H2><P>This program illustrates the use of <A HREF="../stdlibcr/aut_3512.htm"><B><I>auto_ptr</I></B></A> to ensure that pointers held in a vector are deleted when they are removed. Often, we might want to hold pointers to strings, since the strings themselves may be quite large and we'll be copying them when we put them into the vector. Particularly in contrast to a string, an <B><I>auto_ptr</I></B> is quite small: hardly bigger than a pointer. (Note that the program runs as is because the vector includes memory.)</P><A HREF="sidebar1.htm#sidebar77"><IMG SRC="images/note.gif" BORDER=0> <STRONG>Obtaining the Sample Program.</STRONG></A><PRE>#include <vector>#include <memory>#include <string> int main(){ { // First the wrong way vector<string*> v; v.insert(v.begin(), new string("Florence")); v.insert(v.begin(), new string("Milan")); v.insert(v.begin(), new string("Venice")); // Now remove the first element v.erase(v.begin()); // Whoops, memory leak // string("Venice") was removed, but not deleted // We were supposed to handle that ourselves } { // Now the right way vector<auto_ptr<string> > v; v.insert(v.begin(), auto_ptr<string>(new string("Florence"))); v.insert(v.begin(), auto_ptr<string>(new string("Milan"))); v.insert(v.begin(), auto_ptr<string>(new string("Venice"))); // Everything is fine since auto_ptrs transfer ownership of // their pointers when copied // Now remove the first element v.erase(v.begin()); // Success // When auto_ptr(string("Venice")) is erased (and destroyed) // string("Venice") is deleted } return 0;}</PRE><BR><HR><A HREF="dec_3723.htm"><IMG SRC="images/prev.gif"></A> <A HREF="booktoc1.htm"><IMG SRC="images/toc.gif"></A><A HREF="tindex1.htm"><IMG SRC="images/tindex.gif"></A><A HREF="com_8038.htm"><IMG SRC="images/next.gif"></A><P>©Copyright 1996, Rogue Wave Software, Inc.</P></BODY></HTML>
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -