将 std::unique_ptr 返回给多态类对象的正确方法 [英] The correct way of returning std::unique_ptr to an object of polymorphic class

查看:90
本文介绍了将 std::unique_ptr 返回给多态类对象的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下类层次结构:

Let's say I have the following hierarchy of classes:

struct Base 
{
};

struct Derived : public Base 
{ 
    void DoStuffSpecificToDerivedClass() 
    {
    } 
};

以及以下工厂方法:

std::unique_ptr<Base> factoryMethod()
{
    auto derived = std::make_unique<Derived>();
    derived->DoStuffSpecificToDerivedClass();
    return derived; // does not compile
}

问题是,return 语句无法编译,因为 std::unique_ptr 没有支持协方差的复制构造函数(这是有道理的,因为它没有有任何复制构造函数),它只有一个支持协方差的移动构造函数.

The problem is, the return statement does not compile, because std::unique_ptr does not have a copy constructor with covariance support (which makes sense since it does not have any copy constructors), it only has a move constructor with covariance support.

解决这个问题的最佳方法是什么?我可以想到两种方法:

What is the best way to make solve this problem? I can think of two ways:

return std::move(derived); // this compiles
return std::unique_ptr<Base>(derived.release()); // and this compiles too

编辑 1: 我使用 Visual C++ 2013 作为我的编译器.returnderived 的原始错误消息如下所示:

EDIT 1: I'm using Visual C++ 2013 as my compiler. The original error message for return derived looks like this:

Error   1   error C2664: 'std::unique_ptr<Base,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : cannot convert argument 1 from 'std::unique_ptr<Derived,std::default_delete<Derived>>' to 'std::unique_ptr<Derived,std::default_delete<Derived>> &&'

编辑 2:它是一个从标准 VS 2013 模板新创建的控制台应用程序.我没有调整任何编译器设置.编译器命令行如下所示:

EDIT 2: It is a freshly created console app from a standard VS 2013 template. I haven't tweaked any compiler settings. Compiler command line looks like this:

调试:

/Yu"stdafx.h" /GS /analyze- /W3 /Zc:wchar_t /ZI /Gm /Od /sdl /Fd"Debug\vc120.pdb" /fp:precise /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /RTC1 /Gd /Oy- /MDd /Fa"Debug\" /EHsc /nologo /Fo"Debug\" /Fp"Debug\CppApplication1.pch" 

发布:

/Yu"stdafx.h" /GS /GL /analyze- /W3 /Gy /Zc:wchar_t /Zi /Gm- /O2 /sdl /Fd"Release\vc120.pdb" /fp:precise /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /Gd /Oy- /Oi /MD /Fa"Release\" /EHsc /nologo /Fo"Release\" /Fp"Release\CppApplication1.pch" 

推荐答案

您可以这样做:

return std::move(derived);

这样你就告诉编译器不需要拷贝,满足unique_ptr的要求.如果类型完全匹配,您不需要显式指定 move,但在这种情况下您需要这样做.

That way you tell the compiler no copy is needed, which satisfies the requirements of unique_ptr. If the types matched perfectly you should not need to explicitly specify move, but in this case you do.

这篇关于将 std::unique_ptr 返回给多态类对象的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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