[英]Why does static_cast(*this) to a base class create a temporary copy?
I'm reading Effective C++ and came across this example: 我正在阅读Effective C ++并遇到了这个例子:
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
...
};
The book says: 这本书说:
What you might not expect is that it does not invoke that function on the current object!
您可能没想到的是它不会在当前对象上调用该函数! Instead, the cast creates a new, temporary copy of the base class part of *this, then invokes onResize on the copy!
相反,强制转换创建了* this的基类部分的新临时副本,然后在副本上调用onResize!
Why does static_cast (above code) create a new copy? 为什么static_cast(上面的代码)创建一个新副本? Why not just just use the base class part of the object?
为什么不只是使用对象的基类部分?
Because this code asks to create a new object. 因为此代码要求创建一个新对象。 This code wants to make a
Window
object from *this
— which can be done using the copy constructor of Window
. 这段代码想从
*this
创建一个Window
对象 - 这可以使用Window
的复制构造函数来完成。
What you want instead is this: 你想要的是这样的:
static_cast<Window&>(*this).onResize();
// ^
// note the &
This means I want to make a Window&
from *this
— which is an implicit conversion from a derived class' reference ( *this
is a SpecialWindow&
) to a Window&
reference. 这意味着我想创建一个
Window&
from *this
- 这是从派生类' reference ( *this
is SpecialWindow&
)到Window&
reference的隐式转换 。
However, it's better to just call the specific version of the member function onResize()
you want to call: 但是,最好只调用要调用的成员函数
onResize()
的特定版本 :
Window::onResize(); // equivalent to this->Window::onResize();
That's because the code is casting to a value Window
instead of a reference Window&
. 那是因为代码正在转换为值
Window
而不是引用Window&
。 According to the standard, this form of casting is equivalent to calling (C++11 §5.2.9/4 = C++03 §5.2.9/2) 根据标准,这种形式的铸造相当于调用(C ++11§5.2.9/ 4 = C ++03§5.2.9/ 2)
Window __t (*this);
__t.onResize();
which invokes the copy-constructor of Window
, and performs onResize on that copy. 它调用
Window
的复制构造函数,并在该副本上执行onResize。
(The proper way of calling a method of the superclass is (调用超类方法的正确方法是
Window::onResize();
) )
Because you are casting actual object not a pointer or reference. 因为您正在转换实际对象而不是指针或引用。 It's just the same way casting
double
to int
creates new int
- not reusing the part of double
. 这只是以同样的方式铸造
double
来int
创造新的int
-不重用的部分double
。
Contrast: 对比:
static_cast<Window>(*this)
with: 有:
static_cast<Window&>(*this)
One calls the copy constructor, the other does not. 一个调用复制构造函数,另一个不调用。 Does that help?
这有帮助吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.