微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/c/114987.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐