Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique_ptr ownership error when return unique_ptr from function [duplicate]

Tags:

c++

unique-ptr

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
like image 465
Phlox Midas Avatar asked Nov 30 '25 19:11

Phlox Midas


1 Answers

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.

like image 90
Jesse Good Avatar answered Dec 03 '25 08:12

Jesse Good