Having fun with C++’s auto_ptr
Sometimes RAII is difficult.
The following code compiles without errors or warnings on Windows using Visual Studio 2005:
#include <iostream>
#include <memory>
namespace Test
{
class Foo
{
public:
bool should_do_stuff() { return false; }
};
class Bar
{
public:
Bar(std::auto_ptr<Foo> fp) : _fp(fp) {}
void do_stuff() {
if(_fp->should_do_stuff())
std::cout << "Do stuff" << std::endl;
else
std::cout << "Don't do stuff" << std::endl;
}
private:
std::auto_ptr<Foo> _fp;
};
} // Test
int
main()
{
std::auto_ptr<Test::Foo> fp;
fp = new Test::Foo;
bp->do_stuff();
return(0);
}
However, it throws an exception just at the end of execution. Hmm, strange. Compiling it using GCC fails—it complains about the lack of an applicable operator= function.
This is what the assignment should look like:
fp = std::auto_ptr<Test::Foo>(new Test::Foo);
With that change GCC accepts it, and Microsoft’s compiler generates exception-free code.