为什么是“虚拟"?在 C++ 中隐式传播的方法? [英] Why is the "virtuality" of methods implicitly propagated in C++?

查看:43
本文介绍了为什么是“虚拟"?在 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
};

这篇关于为什么是“虚拟"?在 C++ 中隐式传播的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆