#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
class base
{
public:
base()
: f(boost::bind(&base::foo,this)){}
virtual ~base(){}
virtual void foo() { std::cout << "class base" << std::endl; }
boost::function<void(void)> f;
};
class a : public base
{
public:
void foo() { std::cout << "class a" << std::endl; }
};
int main()
{
base* b = new a();
b->f();
return 0;
}
I can guarantee that "f" will never be invoked until "a" has been
instantiated. However I get warnings when compiling, complaining that
accessing "this" during the constructor is a bad idea. I was wondering
what kind of things could go wrong when using "this" during the
constructor, other than some of the more obvious things like accessing
members that haven't been constructed yet etc..
-zenni
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
> what kind of things could go wrong when using "this" during the
> constructor, other than some of the more obvious things like accessing
> members that haven't been constructed yet etc..
This is answered in the C++ FAQ
[10.7] Should you use the this pointer in the constructor?
http://www.parashift.com/c++-faq-lite/ctors.html
regards,
Jyoti
Accordingly to Standard 3.8/5 program has undefined behaviour when
this pointer is used to call a non-static member function of the
object before the lifetime of the object is started. I guess UB is
kind of thing that is definitely very very wrong :).
Regards