为什么“虚拟”的方法在C ++中隐式传播? [英] Why is the "virtuality" of methods implicitly propagated in C++?
问题描述
删除停止方法virtuality传播的能力的原因是什么?
What is the reason for removing the ability to stop the propagation of methods virtuality?
让我更清楚:在C ++中,无论你写virtual void foo )或void foo()在派生类中,它将是虚拟的,只要在基类中,foo被声明为virtual。
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()将导致一个虚拟表查找(如果derived2函数覆盖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()也不会是虚拟的
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
};
这篇关于为什么“虚拟”的方法在C ++中隐式传播?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!