为什么编译器会使用下面的' datum::rotate() '的虚调用?
Why would the compiler use a virtual call for `datum::rotate()` below?
在S. Lippman的"Inside the c++ Object Module"的第26页,您会发现以下代码片段:
void rotate(
X datum,
const X *pointer,
const X &reference )
{
// cannot determine until run-time
// actual instance of rotate() invoked
(*pointer).rotate();
reference.rotate();
// always invokes X::rotate()
datum.rotate();
}
main() {
Z z; // a subtype of X
rotate( z, &z, z );
return 0;
}
和本段:
The two invocations through pointer and reference are resolved dynamically. In this example, they both
invoke Z::rotate(). The invocation through datum may or may not be invoked through the virtual
mechanism; however, it will always invoke X::rotate().
当然,datum.rotate()
总是通过静态调用来调用的。为什么编译器会在这里使用虚调用?
编译器可能会选择使用虚调用,即使这样做是不必要的。标准并没有说编译器"必须"将其转换为静态调用。只要调用了"正确的"函数,编译器就完成了它的工作。
编辑:似乎标准(至少n3337)并没有确切地说编译器应该如何被调用-它基本上只是说注意:虚函数调用的解释取决于它所针对的对象的类型调用(动态类型),而非虚成员函数调用的解释取决于只能在表示该对象的指针或引用的类型(静态类型)上使用(5.2.2)。-结束提示
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- 如何用参数值调用函数(仅在运行时已知)
- glm::rotate()调用编译失败
- 为什么编译器会使用下面的' datum::rotate() '的虚调用?