
Hi there, I'm doing some job interview preparations. Always a good idea to go back to the basics and tinker around a bit. I came across a surprising behavior when using std::vector, std::auto_ptr, and boost::bind. Basically, I have a vector of auto_ptrs which is copied into a second vector, thus the first vector's auto_ptr loss their resource and point to nowhere. Basic stuff, as I said. Now, when I try to use an auto_ptr from the first vector using boost::bind everything still works. Meaning the code doesn't fail, although it should. I find that surprising. Why is boost::bind recreating the resource? Here is a my example code: #include <algorithm> #include <iostream> #include <vector> #include <boost/bind.hpp> using namespace std; struct A { A() { cout << "A::A();"; } ~A() { cout << "A::~A();"; } void foo() { cout << "A::foo();"; } }; auto_ptr< A > allocate_A() { return auto_ptr<A>( new A() ); } void call_foo( auto_ptr< A > p ) { p->foo(); } int main() { std::vector< auto_ptr< A > > v( 100 ); generate_n( v.begin(), 100, allocate_A ); for_each( v.begin(), v.end(), boost::bind( &A::foo, _1 )); std::vector< auto_ptr< A > > v2( 100 ); copy( v.begin(), v.end(), v2.begin() ); // auto_ptr in v should be empty now. // this fails //v[0]->foo(); // this fails //for_each( v.begin(), v.end(), call_foo ); // this doesn't fail for_each( v.begin(), v.end(), boost::bind( &A::foo, _1 )); return 0; } I'm using MSVC10 Express. Regards, Christian