为什么是“虚拟"?在 C++ 中隐式传播的方法?
移除阻止方法虚拟性传播的能力的原因是什么?
What is the reason for removing the ability to stop the propagation of methods virtuality?
让我更清楚一点:在 C++ 中,无论你在派生类中编写virtual void foo()"还是void foo()",只要在基类中声明 foo,它就会是虚拟的.
Let me be clearer: In C++, whether you write "virtual void foo()" or "void foo()" in the derived class, it will be virtual as long as in the base class, foo is declared virtual.
这意味着通过派生* 指针调用 foo() 将导致虚拟表查找(如果派生2 函数覆盖 foo),即使程序员不希望这种行为.
This means that a call to foo() through a derived* pointer will result in a virtual table lookup (in case a derived2 function overrides foo), even if this behavior is not wanted by the programmer.
让我举一个例子(对我来说看起来很明显),说明阻止虚拟传播有什么用处:
Let me give you an example (that looks pretty blatant to me) of how it would be useful to stop virtuality propagation:
template <class T>
class Iterator // Here is an iterator interface useful for defining iterators
{ // when implementation details need to be hidden
public:
virtual T& next() { ... }
...
};
template <class T>
class Vector
{
public:
class VectIterator : public Iterator<T>
{
public:
T& next() { ... }
...
};
...
};
在上面的示例中,可以使用 Iterator 基类以更清晰和面向对象的方式实现类型擦除"的一种形式.(参见 http://www.artima.com/cppsource/type_erasure.html类型擦除的示例.)
In the example above, the Iterator base class can be used to achieve a form of "type erasure" in a much more clearer and Object-Oriented way. (See http://www.artima.com/cppsource/type_erasure.html for an example of type erasure.)
但是,在我的示例中,可以直接使用 Vector::VectIterator 对象(在大多数情况下都会这样做),以便在不使用接口的情况下访问真实对象.
But still, in my example one can use a Vector::VectIterator object directly (which will be done in most cases) in order to access the real object without using the interface.
如果没有传播虚拟性,即使从指针或引用调用 Vector::VectIterator::next() 也不会是虚拟的,并且能够内联并高效运行,就像 Iterator 接口没有一样'不存在.
If virtuality was not propagated, calls to Vector::VectIterator::next() even from a pointer or reference would not be virtual and would be able to be inlined and to run efficiently, just as if the Iterator interface didn't exist.
推荐答案
C++11为此添加了上下文关键字final
.
C++11 added the contextual keyword final
for this purpose.
class VectIterator : public Iterator<T>
{
public:
T& next() final { ... }
...
};
struct Nope : VecIterator {
T& next() { ... } // ill-formed
};
相关文章