Can i pass auto_ptr by reference to functions?
Asked Answered
K

1

7

is the following function OK:

void DoSomething(auto_ptr< … >& a)....
Klansman answered 21/3, 2010 at 9:57 Comment(0)
M
19

You can do it but I'm not sure why you would want to do it.

If you're using the auto_ptr to indicate ownership of the ptr (as people generally do), then you only need to pass the auto_ptr to a function if you want to transfer ownership of the ptr to the function, in which case you would pass the auto_ptr by value:

void DoSomething(auto_ptr<int> a)

So any code calling DoSomething relinquishes ownership of the ptr:

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

Otherwise just pass the ptr by value:

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

...

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

or pass a ref to the pointed to object:

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

...

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

The second is usually preferable as it makes it more explicit that DoSomething is unlikely to attempt to delete the object.

Muddler answered 21/3, 2010 at 11:50 Comment(4)
passing the pointer by value is not safe - memory leaks could occur. creating the object without 'new' means that the object will be on the stack - not sure it is the best approach either.Klansman
@eriks: Memory leaks can occur in many situations; even if you pass an auto_ptr by reference, someone could call delete ptr.get() which would be worse. Passing pointers by value passes no information about transfer of ownership or the correct form of deletion so - in the absence of documentation to the contrary - I wouldn't expect the callee to delete the object pointed to.Inerney
@eriks: You won't get memory leak, you'll just get dangling pointers.Larisa
@eriks: I've expanded my examples to hopefully clarify.Muddler

© 2022 - 2024 — McMap. All rights reserved.