转换std :: unique_ptr< Derived> to std :: unique_ptr< Base> [英] Converting std::unique_ptr<Derived> to std::unique_ptr<Base>

查看:138
本文介绍了转换std :: unique_ptr< Derived> to std :: unique_ptr< Base>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有处理基类和派生类的工厂函数:

Let's say I have factory functions dealing with base and derived classes:

#include <memory>

using namespace std;

struct B { virtual ~B() {} };
struct D : B {};

unique_ptr<B> MakeB()
{
    auto b = unique_ptr<B>( new B() );
    return b; // Ok!
}

unique_ptr<B> MakeD()
{
    auto d = unique_ptr<D>( new D() );
    return d; // Doh!
}



在上面的最后一行,我需要 move d)为了使它工作,否则我得到错误:从无效的转换std :: unique_ptr< D> std :: unique_ptr< D>&&< / code>。我的直觉说,在这个上下文中,编译器应该知道它可以隐式地使 d 一个右值,并将其移动到基本指针,但它不是。

On the last line above, I need move(d) in order to make it work, otherwise I get "Error: invalid conversion from std::unique_ptr<D> to std::unique_ptr<D>&&." My intuition said that in this context, the compiler should know that it could implicitly make d an rvalue and move it into the base pointer, but it doesn't.

这是我的编译器(gcc 4.8.1和VS2012)不一致吗? unique_ptr 的预期设计?标准中的缺陷?

Is this a non-conformancy in my compilers (gcc 4.8.1 and VS2012)? The intended design of unique_ptr? A defect in the standard?

推荐答案

编译器的行为是正确的。当类型相同时,只有一个隐式移动,因为隐式移动是指编译器在实际允许的情况下无法执行复制删除操作(见12.8 / 31和12.8 / 32)。

The compiler's behaviour is correct. There is only an implicit move when the types are the same, because implicit move is specified in terms of the compiler failing to perform copy elision in cases where it is actually allowed (see 12.8/31 and 12.8/32).

12.8 / 31(copy elision):

12.8/31 (copy elision):


类返回类型,当表达式是具有与函数返回类型相同的cv无限制类型的非易失性自动对象(除函数或catch子句参数之外)的名称 ...

in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type...

12.8 / 32(隐式移动):

12.8/32 (implicit move):


当满足复制操作的精度的标准[...]时,首先执行用于为复制选择构造函数的重载分辨率,如同对象由右值指定。

这篇关于转换std :: unique_ptr&lt; Derived&gt; to std :: unique_ptr&lt; Base&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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