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

Phl*_*das 3 c++ unique-ptr

我是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
Run Code Online (Sandbox Code Playgroud)

Jes*_*ood 13

删除const,编译器在按const值返回时被强制使用复制构造函数.按const价值返回几乎没有意义,强烈建议反对.请参阅const值返回的目的?欲获得更多信息.