从函数返回Unique_ptr时出现Unique_ptr所有权错误

unique_ptr ownership error when return unique_ptr from function

本文关键字:Unique ptr 所有权 错误 函数 返回      更新时间:2023-10-16

我是新来的unique_ptr。一切都很好,直到我遇到一个函数返回一个新的unique_ptr。编译器似乎抱怨不止一个对象可能拥有unique_ptr。我不确定如何满足编译器的抱怨。如有任何帮助,不胜感激。

void Bar::Boo()
{
    ...
    // m_Goals is of type std::unique_ptr<Goals>
    auto x = m_Goals->Foo(); // error: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
    //auto x = std::move( m_Goals->Foo() ); // same error
    ...
}

const std::unique_ptr<Goals> Goals::Foo()
{
    std::unique_ptr<Goals> newGoals( new Goals() );
    ...
    return newGoals;
    // also tried "return std::move( newGoals )" based on http://stackoverflow.com/questions/4316727/returning-unique-ptr-from-functions
} // this function compiles

删除const,当您返回const值时,编译器将强制使用复制构造函数。通过const值返回几乎没有任何意义,强烈建议不要返回。请参见const值返回的目的?查看更多信息。