c – 与std :: unique_ptr的clang错误

我有一个叫做IList的基础对象.然后我有VectorList,继承IList.

那么我有这样的功能

std::unique_ptr<IList> factory(){
    auto vlist = std::make_unique<VectorList>();
    return vlist;
}

这在gcc下编译没有问题,但是clang提供了以下错误

test_file.cc:26:9: error: no viable conversion from 'unique_ptr<VectorList,default_delete<VectorList>>' to
      'unique_ptr<IList,default_delete<IList>>'
        return vlist;

如何正确处理这种错误

解决方法

看来(你的版本)Clang在这方面仍然遵循C11的行为.在C 11中,在这种情况下,您必须使用std :: move,因为vlist的类型与返回类型不同,因此“返回一个左值,先将其作为rvalue尝试”的子句不适用.

在C14中,这种“需要相同类型”的限制被解除了,所以在C14中,你不应该在return语句中需要std :: move.但是如果您需要使用当前工具链编译代码,只需将其添加到:

return std::move(vlist);

这个确切的C 11的措词是:

12.8/32 When the criteria for elision of a copy operation are met or would be met save for the fact that the source
object is a function parameter,and the object to be copied is designated by an lvalue,overload resolution to
select the constructor for the copy is first performed as if the object were designated by an rvalue. …

必须符合复印件的标准(包括“同类型”);它们只是稍微扩展到覆盖参数.

在C14(N4140)中,措辞更广泛:

12.8/32 When the criteria for elision of a copy/move operation are met,but not for an exception-declaration, and the
object to be copied is designated by an lvalue,or when the expression in a return statement is a (possibly
parenthesized) id-expression that names an object with automatic storage duration declared in the body or
parameter-declaration-clause of the innermost enclosing function or lambda-expression,
overload resolution
to select the constructor for the copy is first performed as if the object were designated by an rvalue.

(重点是我)

如您所见,退货条件不再需要复印精密标准.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...