Re: Passing *this in constructor
On Jun 7, 1:13 am, Frank Birbacher <bloodymir.c...@gmx.net> wrote:
Victor Bazarov schrieb:
Note, that the Bar subobject is initialised before the
construction of the 'Foo' subobject begins.
However James seemed to say you cannot cast "*this" into a
base class reference:
struct Base {};
struct HoldBase {
HoldBase(Base&);
};
struct Derived : Base {
Derived()
: Base(), hold(*this)
{}
HoldBase hold;
};
This transforms "*this" into a base class reference during
initialization. I interpreted James posting this way and
concluded the above must be invalid/undefined behaviour. And
this seems rather odd, don't you think?
It is undefined behavior, and I think it rather odd, too. The
reason I know it's undefined behavior, however, is that I ran
into an actual case where it didn't work, went to write up a
compiler bug report, and when trying to find where the standard
said it had to work, found just the opposite.
One way around it is to use a wrapper class which returns the
pointer---you can't convert the pointer, but you can call member
funtions on fully constructed sub-objects, so something like:
template< typename Base >
struct BaseWrapper
{
Base object ;
Base* ptr() ;
Base& ref() ;
} ;
struct Derived : BaseWrapper< Base >
: hold( ref() )
{
} ;
Although useful in some specific cases (I use it when deriving
from both a specific streambuf and istream or ostream), it is
awkward and overly complex in the general case. And if the
compiler is required to get its pointer conversions correct in
this case, why can't it do so in the other case?
--
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