Infinite loop using static_cast on this pointer
Suppose I have two classed Base
and Derived
, i.e.:
#include <iostream>
class Base {
public:
Base ()
: m_name("Base")
{
}
virtual ~Base ()
{
}
virtual void method (std::ostream & out) const
{
out << m_name << std::endl;
}
protected:
Base (std::string name)
: m_name(name)
{
}
private:
std::string m_name;
};
class Derived : public Base {
public:
Derived ()
: Base(开发者_如何学Python"Derived")
{
}
virtual ~Derived ()
{
}
virtual void method (std::ostream & out) const
{
static_cast<const Base * const>(this)->method(out);
}
};
If I call Derived::method()
, I get an infinite loop.
int main ()
{
Derived d;
d.method(std::cout);
return 0;
}
Of course. I can change static_cast<const Base * const>(this)->method(out);
to Base::method(out)
and everything will run fine, but I am interested in the reason behind this behavior.
Shouldn't both have the same behavior?
So can anybody out there explain what is happening here?
On a side note, I compiled the code with g++ -Wall -Wextra -O2 -g foo.cpp -o foo
.
Is there any chance to get a warning for this kind of code?
Probably you already guessed: static_cast<const Base * const>(this)->method(out);
is a virtual call, which means the function is called within itself. In this case, it would lead to stack overflow. Base::method(out)
is not a virtual call.
You declared the member function as virtual. Put simply, this means that the derived class' implementation will be called when you access the object through a pointer to the base class.
精彩评论