void anotherMethod(auto_ptr<Foo> foo)
{
cout << "Taken ownership. " << foo->getAString() << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
auto_ptr<Foo> foo(new Foo);
cout << foo->getAString() << endl;
anotherMethod(foo);
// this will throw error as the pointer is deleted
cout << "From main again " << foo->getAString();
cout << "Ending main" << endl;
return 0;
}
In the avove code, I am trying to pass the auto_ptr
to another function. But doing this will make the another function take ownership and the underlying pointer will be deleted when another functions scope ends. So I am unable to access it in the main
method again. To workaround this issue, I changed the code like
void anotherMethod(const auto_ptr<Foo>& foo)
{
cout << "Taken ownership. " << foo->getAString() << endl;
}
The below code will also work
void anotherMethod(Foo* foo)
{
cout << "Taken ownership. " << foo->getAString() << endl;
}
// in main I called like
auto_ptr<Foo> foo(new Foo);
anotherMethod(foo.get());
I am wondering which one is the best approach? Can anyone help? Also is it a good practice to use auto_ptr
over normal pointers and is it always guranteed the cleanup?