Question of using static_cast on “this” pointer in a derived object to base class

末鹿安然 提交于 2019-12-22 07:20:14

问题


this is an example taken from Effective C++ 3ed, it says that if the static_cast is used this way, the base part of the object is copied, and the call is invoked from that part. I wanted to understand what is happening under the hood, will anyone help?

class Window {                                // base class
public:
  virtual void onResize() { }                 // base onResize impl
};

class SpecialWindow: public Window {          // derived class
public:
  virtual void onResize() {                   // derived onResize impl;
    static_cast<Window>(*this).onResize();    // cast *this to Window,
                                              // then call its onResize;
                                              // this doesn't work!
                                              // do SpecialWindow-
  }                                           // specific stuff
};

回答1:


This:

static_cast<Window>(*this).onResize();

is effectively the same as this:

{
    Window w = *this;
    w.onResize();
}   // w.~Window() is called to destroy 'w'

The first line creates a copy of the Window base class subobject of the SpecialWindow object pointed to by this. The second line calls onResize() on that copy.

This is important: you never call Window::onResize() on the object pointed to by this; you call Window::onResize() on the copy of this that you created. The object pointed to by this is not touched after you make the copy it.

If you want to call Window::onResize() on the object pointed to by this, you can do so like this:

Window::onResize();



回答2:


Why casting? Just do this if you want to call Window's onResize(),

Window::onResize(); //self-explanatory!

Alright, you can do this same, using static_cast also, but you've to do this way,

   static_cast<Window&>(*this).onResize();
    //note '&' here  ^^


来源:https://stackoverflow.com/questions/4543670/question-of-using-static-cast-on-this-pointer-in-a-derived-object-to-base-clas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!