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
?
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.