Below code has output
Foo created 3
0
doit
Foo destructed 3
I am confused. When an auto_ptr object is assigned to another auto_ptr
object, the control of pointer is transferred from orginal auto_ptr to
target auto_ptr, and orginal auto_ptr points to NULL. Then foo->doit()
should throw a Segmentation Fault in my mind, but the code works fine
just like foo still has the reference.
/* Code */
#include <memory>
class Foo
{
public:
Foo(int v):_v(v) { printf("Foo created %d\n", v); }
~Foo() { printf("Foo destructed %d\n",_v); }
void doit();
int _v;
};
void Foo::doit()
{
printf("doit\n");
}
int main(int argc, char** argv)
{
Foo *f = new Foo(3);
std::auto_ptr<Foo> foo (f);
std::auto_ptr<Foo> foo2 = foo;
printf("%d\n", foo.get());
foo->doit();//this line should cause Segmentation Fault IMO
return 0;
}