[bind] and [function] : question on binding member function

Hi, can someone explain to me why the following code crashes at the third call to "a.call_func" when "str" is dereferenced? Should'nt it crash when "this" is dereferenced? Thanks in advance. typedef boost::function<void (void)> Callback; class A { public: void set_cb_func( Callback cb ) { callback = cb; } void call_func() { callback(); } Callback callback; }; class B { public: B() : str(new std::string) {} ~B() { delete str; } void do_sth() { std::cerr << &(*this) << " " << *str << std::endl; *str += "string"; }; std::string * str; }; int main() { A a; { B b; a.set_cb_func(boost::bind(&B::do_sth, &b)); a.call_func(); a.call_func(); } a.call_func(); return 0; }

can someone explain to me why the following code crashes at the third call to "a.call_func" when "str" is dereferenced? Should'nt it crash when "this" is dereferenced?
IIRC, it's undefined behavior, so it shouldn't anything. But in practice, I guess the compiler just ommits &* in "&*this", so there's no reason for crash.

Add copy constructor: B::B( const B& src ) : str( new std::string( *src.str ) ) { } -- Regards, Ivan Kharin
participants (3)
-
Igor R
-
Ivan Kharin
-
Moritz