gpt4 book ai didi

c++ - 在声明为返回unique_ptr 的函数中返回unique_ptr

转载 作者:行者123 更新时间:2023-12-02 09:49:38 31 4
gpt4 key购买 nike

该代码在函数中返回unique_ptr<Derived>,该函数声明为返回unique_ptr<Base>。使用g++-4.8编译时出现错误,但是使用g++-5.4和g++-7编译时没有错误。这是g++ 4.8的编译器错误,还是我做错了什么?

编码:

#include <memory>

class Base
{
public:
Base() {}
};

class Derived: public Base
{
public:
Derived() : Base() {}
};

std::unique_ptr<Base> func()
{
std::unique_ptr<Derived> derivedPtr = std::unique_ptr<Derived>();
return derivedPtr;
}

int main()
{
std::unique_ptr<Base> basePtr = func();

return 0;
}

g++-4.8的错误:
$ g++-4.8 -std=c++11 test.cpp
test.cpp: In function ?std::unique_ptr<Base> func()?:
test.cpp:19:9: error: cannot bind ?std::unique_ptr<Derived>? lvalue to ?std::unique_ptr<Derived>&&?
return derivedPtr;
^
In file included from /usr/include/c++/4.8/memory:81:0,
from test.cpp:2:
/usr/include/c++/4.8/bits/unique_ptr.h:169:2: error: initializing argument 1 of ?std::unique_ptr<_Tp, _Dp>::unique_ptr(std::unique_ptr<_Up, _Ep>&&) [with _Up = Derived; _Ep = std::default_delete<Derived>; <template-parameter-2-3> = void; _Tp = Base; _Dp = std::default_delete<Base>]?
unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept

^

g++-7没有错误:
$ g++-7 -std=c++11 test.cpp
$

如果我将 func更改为 return std::move(derivedPtr);,则代码将在所有 g++版本上编译。虽然我想了解我的原始代码是否有效。

最佳答案

CWG 1579追溯地适用于C++ 11,但是旧的编译器版本可能会错过这一点。

关于c++ - 在声明为返回unique_ptr <Base>的函数中返回unique_ptr <Derived>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61288827/

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