Dereferencing this in constructors initialiser list

M

Martin Zimmermann

Hi.

Is it allowed to dereference 'this' in a constructors initialiser list
to initialize a reference? (for later use)

Is this code legal or illegal?

class Foo;

class Bar
{
public:
Bar(Foo& foo)
: foo_(foo)
{
}
private:
Foo& foo_;
};

class Foo
{
public:
Foo()
: bar_(*this)
{
}
private:
Bar bar_;
};

int main()
{
}

Bye.
 
T

tom_usenet

Hi.

Is it allowed to dereference 'this' in a constructors initialiser list
to initialize a reference? (for later use)

Yes. You can even do that before the constructor has even started. You
can only use that lvalue to access things that have already been
initialized (such as earlier base classes, earlier member variables
(in class declaration order)).

This is perfectly valid:

Foo* mem = static_cast<Foo*>(malloc(sizeof *mem));
assert(mem);
Foo& f = *mem;
//don't use f until it has been constructed!
new(mem) Foo();
//now you can use f safely.

Tom
 
R

Rob Williscroft

Martin Zimmermann wrote in in
comp.lang.c++:
Hi.

Is it allowed to dereference 'this' in a constructors initialiser list
to initialize a reference? (for later use)

Is this code legal or illegal?

class Foo;

class Bar
{
public:
Bar(Foo& foo)
: foo_(foo)
{
}
private:
Foo& foo_;
};

class Foo
{
public:
Foo()
: bar_(*this)
{
}
private:
Bar bar_;
};

int main()
{
}

Bye.

Simple logic should suffice. In order to initialize the bar_
subobject 'this' must be dereferenced (this->bar_) anyway,
so yes you can.

Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top