【问题标题】:unique_ptr ownership error when return unique_ptr from function [duplicate]从函数返回unique_ptr时出现unique_ptr所有权错误[重复]
【发布时间】:2013-06-14 10:24:50
【问题描述】:

我是 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

【问题讨论】:

    标签: c++ unique-ptr


    【解决方案1】:

    去掉const,当你通过const值返回时,编译器会强制使用复制构造函数。通过const 值返回几乎没有意义,强烈建议不要。请参阅Purpose of returning by const value? 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2011-05-18
      • 1970-01-01
      • 2022-12-05
      • 2019-09-11
      • 2020-03-07
      相关资源
      最近更新 更多