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 http://stackoverflow.com/questions/4316727/returning-unique-ptr-from-functions
} // this function compiles
4

1 回答 1

13

去掉const,当你按值返回时,编译器被迫使用复制构造const函数。按值返回几乎没有意义,const强烈建议不要。请参阅按 const 值返回的目的?了解更多信息。

于 2013-06-18T09:12:16.627 回答