Reputation: 18127
I've got the following sample code:
#include <iostream>
#include <auto_ptr.h>
class A
{
public:
A(){ std::cout << "A ctor" << std::endl;}
~A() {std::cout << "A dtor" << std::endl;}
void bar(){std::cout << "bar()" << std::endl;}
};
void foo(std::auto_ptr<A> a)
{
std::cout << "foo()" << std::endl ;
}
int main()
{
std::auto_ptr<A> a(new A());
a->bar();
return 0;
}
output:
A ctor
bar()
A dtor
Now if I call foo(a)
, a
will be destructed before calling bar()
:
int main()
{
std::auto_ptr<A> a(new A());
foo(a);
a->bar();
return 0;
}
output:
A ctor
foo()
A dtor
bar()
Why is a
destructed after foo()
is called?
Another thing I don't understand is that if I pass the parameter to foo
by reference, a
will not be destructed after calling foo()
:
void foo(std::auto_ptr<A> &a)
{
std::cout << "foo()" << std::endl ;
}
int main()
{
std::auto_ptr<A> a(new A());
foo(a);
a->bar();
return 0;
}
output:
A ctor
foo()
bar()
A dtor
How is passing by reference affecting the lifetime of auto_ptr
?
Upvotes: 0
Views: 194
Reputation: 2624
The std::auto_ptr is usually not what people expect, the idea was that that it is a safer concept since the ptr is cleared as soon as the object get out of scope. So your "new A" will not be leaked even in case of multiple returns / exception thrown etc.
However as you shown it is also very easy to cause illegal memory access because two auto_ptrs sharing a single pointer is a recipe for disaster.
If you just want a ptr that you can use and not worry about releasing you should use unique_ptr. unique_ptr can't be copied. So you can pass a reference of it but not copy it.
Usually the most useful construct is the shared_ptr which allows multiple owners to share a the same ptr and ensures it will be released when all the owners go out of scope.
All of these are part of c++11 standard library or available via boost library.
Upvotes: 1
Reputation: 28178
auto_ptr
steals ownership upon copying. When you copy it, the copy now holds the pointer to the object, and the original holds nothing.
It's also a deprecated concept. If you have access to C++11, use unique_ptr
instead.
Upvotes: 6
Reputation: 661
The auto_ptr has semantics of transfer ownership. If you pass it by value then ownership is transfered to a temporary object which, of course, will be destroyed when leaves the scope.
Upvotes: 2