加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 与std :: unique_ptr的clang错误

发布时间:2020-12-16 05:19:55 所属栏目:百科 来源:网络整理
导读:我有一个叫做IList的基础对象.然后我有VectorList,继承IList. 那么我有这样的功能: std::unique_ptrIList factory(){ auto vlist = std::make_uniqueVectorList(); return vlist;} 这在gcc下编译没有问题,但是clang提供了以下错误: test_file.cc:26:9: err
我有一个叫做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.

(重点是我)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读