7

以下功能是否OK:

void DoSomething(auto_ptr< … >& a)....
4

1 回答 1

19

你可以做到,但我不确定你为什么要这样做。

如果您使用 auto_ptr 来指示 ptr 的所有权(正如人们通常所做的那样),那么如果您想将 ptr 的所有权转移给函数,则只需将 auto_ptr 传递给函数,在这种情况下,您将通过auto_ptr 按值:

void DoSomething(auto_ptr<int> a)

因此,任何调用 DoSomething 的代码都会放弃 ptr 的所有权:

auto_ptr<int> p (new int (7));
DoSomething (p);
// p is now empty.

否则只需按值传递 ptr :

void DoSomething(int* a)
{...}

...

auto_ptr<int> p (new int (7));
DoSomething (p.get ());
// p still holds the ptr.

或将 ref 传递给指向的对象:

void DoSomething(int& a)
{...}

...

auto_ptr<int> p (new int (7));
DoSomething (*p);
// p still holds the ptr.

第二个通常更可取,因为它更明确地表明 DoSomething 不太可能尝试删除对象。

于 2010-03-21T11:50:20.860 回答