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?
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 standardauto_ptris deprecated andunique_ptris the superior alternative if you are using c++11.The
auto_ptrtemplate class ensures that the object to which it points gets destroyed automatically when control leaves a scope, If you passauto_ptrby 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_ptrby reference is considered a bad design becauseauto_ptrwas 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 anunique_ptrto function by value then you are transferring the ownership of theunique_ptrto the function.In case you are passing a reference of
unique_ptrto 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_ptroperates 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_ptrby 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 forshared_ptris not very expensive for most cases but it might matter in some scenarios, So using either of the two depends on the situation.