Re: casting std::auto_ptr<Derived> to std::auto_ptr<Base> produces compiler warning 'recursive function call'
Robi-Wan-Kenobi wrote:
std::auto_ptr<Derived1> CreateDerived1();
std::auto_ptr<Derived2> CreateDerived2();
std::auto_ptr<Base> CreateBase()
{
if(some condition)
{
return CreateDerived1();
}
else
{
return CreateDerived2();
}
}
So far, nothing surprising.
that won't compile, i have to cast the auto_ptr<Derived...> to
auto_ptr<Base>.
Oh wait: the conclusion "I have to cast" is usually wrong and only shows a
lack of understanding of the issue. Here, no cast should be necessary, as
an auto_ptr can normally be converted to another auto_ptr when a raw
pointer could.
So i tried it like this:
std::auto_ptr<Base> CreateBase()
{
if(some condition)
{
return (std::auto_ptr<Base>)CreateDerived1();
}
else
{
return (std::auto_ptr<Base>)CreateDerived2();
}
}
As noted above, this is the wrong approach, and BTW: you should be tarred
and feathered for even thinking about this type of cast.
No, the problem here is a different one: auto_ptr's move semantics in
combination with the conversion to the baseclass. The move semantics
require that e.g. the assignment takes a non-const reference. It then in
turn zeroes the right hand side. However, CreateDerivedX() return an
auto_ptr which, as a temporary, can not be used in an assignment. auto_ptr
uses a hack, and that is a conversion to a 'ref' type (look up its name, I
forgot), which carries over the content to the target. IOW, the solution
simply involves storing it in a temporary of the same type or removing the
const, i.e. a const_cast<auto_ptr<X>&>(..).
Here i get a compiler warning saying there is a recursive function
call which will cause a stack overflow. (warning C4717 with MSVC)
Would be interesting to know the initial error. Also, some versions of MSVC
predate the standard and also have a non-standard auto_ptr implementation.
Uli
--
Sator Laser GmbH
Gesch?ftsf?hrer: Ronald Boers, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]