c – 与std :: unique_ptr的clang错误

前端之家收集整理的这篇文章主要介绍了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.

(重点是我)

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

原文链接:https://www.f2er.com/c/114987.html

猜你在找的C&C++相关文章