warning: 'this' used in base member initializer list

D

Derek

I get the following warning

warning C4355: 'this' : used in base member initializer list

when I compile the following program with VC6 and VC7 (the latest
GCC and Comeau doesn't think anything is amiss):

class Y;

class X {
public:
X(Y& y) : m_y(y) {}
private:
Y& m_y;
};

class Y {
public:
Y() : m_x(*this) {} // <<<<< warning here
private:
X m_x;
};

int main() {
Y y;
return 0;
}

I'm guessing the warning stems from the fact that I'm passing
the 'this' pointer of a not-yet-fully-constructed object to a
function (X's ctor).

However, I'm not actually using 'this', just passing and storing
it (albeit via reference). Is this safe provided that I don't
try to use X::m_y until the object it refers to is constructed?

Thanks.
 
V

Victor Bazarov

Derek said:
I get the following warning

warning C4355: 'this' : used in base member initializer list

when I compile the following program with VC6 and VC7 (the latest
GCC and Comeau doesn't think anything is amiss):

class Y;

class X {
public:
X(Y& y) : m_y(y) {}
private:
Y& m_y;
};

class Y {
public:
Y() : m_x(*this) {} // <<<<< warning here
private:
X m_x;
};

int main() {
Y y;
return 0;
}

I'm guessing the warning stems from the fact that I'm passing
the 'this' pointer of a not-yet-fully-constructed object to a
function (X's ctor).
Correct.

However, I'm not actually using 'this', just passing and storing
it (albeit via reference). Is this safe provided that I don't
try to use X::m_y until the object it refers to is constructed?

Yes, that's why it's a warning and not an error message.

V
 

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

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top