std::unique_ptr 的 clang 错误

clang error with std::unique_ptr

我有一个名为 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 的类型不同于 return 类型,因此 "when returning an lvalue, try it as an rvalue first" 的子句确实不适用。

在 C++14 中,取消了 "same types required" 的限制,因此在 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. ...

必须满足复制省略的标准(包括 "same type");它们只是稍微扩展以涵盖参数。

在 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 案例不再需要复制省略标准。