Re: Using 'this' in constructor
On Oct 17, 7:04 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
bb wrote:
Is it legal and ok to use 'this' in a constructor as follows:
Class A {
class A
public:
A() : pimpl_(0) {
pimpl_ = new AImpl(this);
}
private:
struct AImpl;
AImpl* pimpl_;
};
No. AImpl is unknown at the point where you're trying to
instantiate it.
Not unknown, just incomplete. (Member function code in a class
is compiled as if it were defined immediately after the class.)
Of course, you can't new an incomplete type, so the code is
still illegal.
If your constructor is defined after 'AImpl' is defined as
well, then yes, it's legal, but keep in mind that the object
is not considered fully constructed until its constructor
completes, so calling member functions can be dangerous,
*generally speaking*.
If *all* your AImpl constructor needs to do is to *store* the
pointer to 'A' somewhere so it can access it later, then yes,
it's going to be OK.
Whether A is complete isn't the problem. Something like:
class A {
public:
A() : p( new AImpl( this ) ) {}
private:
struct AImpl
{
AImpl( A* p ) ;
// ...
} ;
AImpl* p ;
} ;
is legal. (Of course, the names in the example suggest the
compliation firewall idiom, and this would defeat the purpose of
it.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34