C ++克隆习语中协变返回类型的用处? [英] Usefulness of covariant return types in C++ clone idiom?

查看:54
本文介绍了C ++克隆习语中协变返回类型的用处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常的克隆习语使用协变返回类型:

The usual clone idiom makes use of covariant return types:

struct Base {
    virtual Base* clone();
};

struct Derived : public Base {
    Derived* clone();
};

我读过一些东西,以至于协变返回类型是C ++的后来添加,而较早的编译器可能不支持它们.在这种情况下, Derived 类必须声明其 clone 成员函数以返回 Base * .由于使用这种习惯用法时,大概只能通过 Base 指针和/或引用访问 Derived 对象,所以声明返回类型<的真正用途/好处是派生* ?

I've read things to the effect that covariant return types were a later addition to C++, and older compilers may not support them. In this case the Derived class must declare its clone member function to return a Base*. Since, presumably, I'm only accessing Derived objects through Base pointers and/or references when using this idiom, what is the real use/benefit to declaring the return type Derived*?

还有一个相关的问题:

我更喜欢使用智能指针来表示 clone 签名的所有权转移语义.当使用协变返回类型时,这是不可能的,因为 auto_ptr< Derived> auto_ptr< Base> 不协变.(请注意,我不是在寻找关于使用智能指针的讲座,这里仅以 auto_ptr 为例).因此,在这种情况下,是否有任何理由不让 Derived 返回 auto_ptr< Base> ?有没有更好的方式来表达所有权转移的语义?

I would prefer to use smart pointers to express transfer-of-ownership semantics for the clone signature. This is not possible when using covariant return types, as auto_ptr<Derived> is not covariant with auto_ptr<Base>. (Please note that I'm not looking for a lecture on the use of smart pointers -- auto_ptr is just used as an example here). So in this case, is there any reason not to have Derived return auto_ptr<Base>? Is there a better way to express the transfer-of-ownership semantics?

推荐答案

当您有指向 Derived 的指针并想要获得它的副本时,此选项很有用:

It's useful when you have a pointer to Derived and want to get a clone of it:

Derived *ptr = ...;
Derived *clone = ptr->clone();

没有协变量返回类型,则必须进行显式转换:

without covariant return types you must do an explicit cast:

Derived *clone2 = (Derived*)ptr->clone();

请注意, Derived 可能是更多派生类的基类,在这种情况下,它更有意义.

Note that Derived may be a base class for even more derived classes, in that case it makes even more sense.

不幸的是 auto_ptr< Derived> auto_ptr< Base> 不是协变的.因此,在这种情况下,您必须从所有克隆函数中返回相同的类型.

Unfortunately auto_ptr<Derived> and auto_ptr<Base> are not covariant. So you must return the same type from all clone functions in that case.

这篇关于C ++克隆习语中协变返回类型的用处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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