3

I'm new to unique_ptr. Everything was going fine until I came across a function returning a new unique_ptr. The compiler seems to complain about more than one object potentially owning the unique_ptr. I'm not sure how to satisfy the compilers complaint. Any help is appreciated.

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
Phlox Midas
  • 4,093
  • 4
  • 35
  • 56

1 Answers1

13

Remove the const, the compiler is forced to use the copy constructor when you return by const value. There is almost no point in returning by const value and is strongly recommended against. Please see Purpose of returning by const value? for more information.

Community
  • 1
  • 1
Jesse Good
  • 50,901
  • 14
  • 124
  • 166