ami*_*cht 7 c++ smart-pointers auto-ptr
是以下功能OK:
void DoSomething(auto_ptr< … >& a)....
Run Code Online (Sandbox Code Playgroud)
jon*_*son 17
你可以做到,但我不确定你为什么要这样做.
如果您使用auto_ptr的指示PTR的所有权(如人一般做),那么你只需要auto_ptr的传递给函数,如果你想在PTR的所有权转让给该功能,在这种情况下,您会通过auto_ptr by value:
void DoSomething(auto_ptr<int> a)
Run Code Online (Sandbox Code Playgroud)
所以任何调用DoSomething的代码都放弃了对ptr的所有权:
auto_ptr<int> p (new int (7));
DoSomething (p);
// p is now empty.
Run Code Online (Sandbox Code Playgroud)
否则只需通过值传递ptr:
void DoSomething(int* a)
{...}
...
auto_ptr<int> p (new int (7));
DoSomething (p.get ());
// p still holds the ptr.
Run Code Online (Sandbox Code Playgroud)
或者将ref传递给指向的对象:
void DoSomething(int& a)
{...}
...
auto_ptr<int> p (new int (7));
DoSomething (*p);
// p still holds the ptr.
Run Code Online (Sandbox Code Playgroud)
第二种通常是可取的,因为它更明确地表明DoSomething不太可能尝试删除该对象.