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

3

我对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 https://dev59.com/92855IYBdhLWcg3wfURM
} // this function compiles
1个回答

13

去掉const,编译器会强制使用复制构造函数来返回const值。几乎没有必要通过const值返回,强烈建议不要这样做。更多信息请参见Purpose of returning by const value?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接