2013-06-18 61 views
3

我是unique_ptr的新手。一切都很順利,直到我遇到一個函數返回一個新的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 

回答

13

取出const,編譯器被迫當您通過const返回值使用拷貝構造函數。 const值幾乎沒有返回值,並強烈建議反對。有關更多信息,請參閱Purpose of returning by const value?

+0

非常感謝。 –

相關問題