Reputation: 1544
In the following example, when I pass p
to a function, It gets destroyed as soon as the function func exits
void func(std::auto_ptr<int> p)
{
// deletes p
}
int main()
{
std::auto_ptr<int> p(new int);
func(p);
*p = 1; // run-time error
}
I'm also told that passing smart pointers by reference is very bad design from the book "The C++ Standard Library - Reference by Nicolai M. Josuttis".
Quote:
Allowing an auto_ptr to pass by reference is very bad design and you should always avoid it .....
..... According to the concept of auto_ptrs, it is possible to transfer ownership into a function by using a constant reference.
Is it not possible to pass smart pointers or have I got the wrong idea?
Upvotes: 2
Views: 3313
Reputation: 206656
Is it not possible to pass smart pointers or have I got the wrong idea?
It only applies to auto_ptr
. Also, as per the new C++11 standard auto_ptr
is deprecated and unique_ptr
is the superior alternative if you are using c++11.
The auto_ptr
template class ensures that the object to which it points gets destroyed automatically when control leaves a scope, If you pass auto_ptr
by value in a function, the object is deleted once the scope of the function ends. So essentially you transfer the ownership of the pointer to the function and you don't own the pointer beyond the function call.
Passing an auto_ptr
by reference is considered a bad design because auto_ptr
was specifically designed for transfer of ownership and passing it by reference means that the function may or may not take over the ownership of the passed pointer.
In case of unique_ptr
, If you pass an unique_ptr
to function by value then you are transferring the ownership of the unique_ptr
to the function.
In case you are passing a reference of unique_ptr
to the function if, You just want the function to use the pointer but you do not want to pass it's ownership to the function.
shared_ptr
operates on a reference counting mechanism, so the count is always incremented when copying functions are called and decremented when a call is made to destructor.
Passing a shared_ptr
by reference avoids calls to either and hence it can be passed by reference. While passing it by value appropriately increments and decrements the count, the copy constructor for shared_ptr
is not very expensive for most cases but it might matter in some scenarios, So using either of the two depends on the situation.
Upvotes: 7
Reputation: 1937
You cannot pass a std::auto_ptr, but you can pass a smart pointer that manages the number of references to it, like boost::shared_ptr.
Upvotes: 0