为什么static_cast(*this)到基类会创建一个临时副本
Why does static_cast(*this) to a base class create a temporary copy?
我正在阅读有效的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
...
};
书中写道:
您可能没有想到的是,它不会在当前对象上调用该函数!相反,强制转换会创建*this基类部分的一个新的临时副本,然后在副本上调用onResize!
为什么static_cast(上面的代码)要创建一个新副本?为什么不直接使用对象的基类部分呢?
因为此代码要求创建一个新对象。这段代码想要从*this
生成一个Window
对象——这可以使用Window
的复制构造函数来完成。
你想要的是:
static_cast<Window&>(*this).onResize();
// ^
// note the &
这意味着我想从*this
生成Window&
——这是从派生类'引用(*this
是SpecialWindow&
)到Window&
引用的隐式转换。
但是,最好只调用要调用的成员函数的特定版本onResize()
:
Window::onResize(); // equivalent to this->Window::onResize();
Window
而不是引用Window&
。根据标准,这种铸造形式相当于调用(C++11§5.2.9/4=C++03§5.2.9/2)
Window __t (*this);
__t.onResize();
其调用Window
的副本构造函数并对该副本执行onResize。
(调用超类方法的正确方法是
Window::onResize();
)
因为您正在强制转换实际对象,而不是指针或引用。这与将double
强制转换为int
创建新的int
的方式相同——不重用double
的部分。
对比度:
static_cast<Window>(*this)
带有:
static_cast<Window&>(*this)
一个调用复制构造函数,另一个不调用。这有帮助吗?
相关文章:
- 在为LINUX创建共享库时,如何避免STL的私有/弱副本
- 创建提升::shared_ptr的深层副本
- Eigen - matrix.transpose 会创建矩阵的副本吗?
- 将 MatrixXd 的行传递给要修改的函数,而不在 Eigen 中创建副本
- 创建字符串流副本
- 是否可以在并行区域中为共享 2D 数组创建选定元素的线程本地副本?(共享,私有,障碍:OPenMP)
- C++ 在其自己的类中创建对象的修改副本
- std::可选参数会创建副本吗?
- 使用 lambda 表达式创建线程时,如何为每个线程提供自己的 lambda 表达式副本
- C++ 如何创建链表的副本作为类对象
- MSVC 2017 在共享库中创建模板函数的副本
- 我如何创建一个双重指针的深层副本,涉及其他类(C )
- 是 std::make_pair 在将对象添加到地图时创建副本
- 阻止用户创建班级对象的副本,但允许动态的对象有什么好处
- 取消引用指针以创建数组的副本
- 创建std :: vector减去一个元素的副本的最快方法
- 此分配是否创建副本
- C++ Qt如何通过小的更改创建GUI的副本
- C++ STL:在创建 std::string 的 const 副本时将更改 c_str()
- 使用矢量push_back代码创建对象副本时遇到问题