gpt4 book ai didi

c++ - std::unique_ptr 的 clang 错误

转载 作者:可可西里 更新时间:2023-11-01 15:05:18 25 4
gpt4 key购买 nike

我有一个名为 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 在这方面仍然遵循 C++11 的行为。在 C++11 中,您必须在这种情况下使用 std::move,因为 vlist 的类型与返回类型不同,因此 "返回左值时,先将其作为右值尝试”不适用。

在 C++14 中,取消了“需要相同类型”的限制,因此在 C++14 中,您不需要在 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. ...

必须满足复制省略的标准(包括“相同类型”);它们只是稍微扩展以涵盖参数。

在 C++14 (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.

(强调我的)

如您所见,return 案例不再需要复制省略标准。

关于c++ - std::unique_ptr 的 clang 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32742741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com