*this in initializer list

A

Alexander Stippler

I know using this in a class initializer list has to be dealt with with
care. I fear for "*this" it is even worse. Is it legal at all - what
does the standard say?
My situation is somewhat like:

struct B;

struct A
{
A(const B &_b) : b(_b) {}

const B &b;
};

struct B
{
B() : a(*this) {}
A a;
};

I just want this reference. No member access or similar (in the
construction process).
Allowed (and reasonable?) by standard or not?

best regards,
Alex
 
P

peter koch

I know using this in a class initializer list has to be dealt with with
care. I fear for "*this" it is even worse. Is it legal at all - what
does the standard say?
My situation is somewhat like:

struct B;

struct A
{
        A(const B &_b) : b(_b) {}

        const B &b;

};

struct B
{
        B() : a(*this) {}
        A a;

};

I just want this reference. No member access or similar (in the
construction process).
Allowed (and reasonable?) by standard or not?

best regards,
        Alex

This is perfectly safe and allowed in the standard.

/Peter
 
M

Marcel Müller

Alexander said:
struct B;

struct A
{
A(const B &_b) : b(_b) {}

const B &b;
};

struct B
{
B() : a(*this) {}
A a;
};

I just want this reference. No member access or similar (in the
construction process).
Allowed (and reasonable?) by standard or not?

This is OK in picipal. A typical parent child relation with object lifetime.
But you *must* not dereference the pointer (or reference) before the
contructor of B has completed. And also think about the case when B() or
one of it's subfunctions throws and A's destructor is called.

Marcel
 

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,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top