开发者

Infinite loop using static_cast on this pointer

开发者 https://www.devze.com 2023-01-16 07:47 出处:网络
Suppose I have two classed Base and Derived, i.e.: #include <iostream> class Base { public: Base ()

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消