Re: Passing *this in constructor
Frank Birbacher wrote:
Hi!
James Kanze schrieb:
The answer is "yes, you can" in this simple case. If the object
expects a reference to a base class, however, you have undefined
behavior (and I've encountered cases where it doesn't work),
since conversion to base is also undefined behavior.
Wait a second. What's that? Has the following undefined behaviour?
struct Foo {
private:
//..lots of member variables needing initialisation
string name;
Bar whatever;
protected:
void run();
};
struct Runner : Foo
{
Runner();
~Runner();
boost::thread myThread;
};
Runner::Runner()
: Foo()
, myThread(bind(&Foo::run, this))
{}
Runner::~Runner()
{
myThread.interrupt();
myThread.join();
}
Maybe this doesn't actually force the conversion of "this" to "Foo*",
but it's an example of what I currently need in some code. I just want
to know some rules about this. So when does it become dangerous?
See 12.7/2. I can't claim full understanding of it, but it seems to say
that since in your code the construction of 'Foo' has completed by the
time 'myThread' is initialised by 'bind', it's OK. Conversion of 'this'
into 'Foo' would have undefined behaviour in this case:
class Foo;
class Bar {
public:
Bar(Foo*); // needs a pointer to Foo
};
class Fubar : public Bar, public Foo {
public:
Fubar() : Bar(this), Foo() {}
};
Note, that the Bar subobject is initialised before the construction of
the 'Foo' subobject begins.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask