加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 从函数返回unique_ptr时的unique_ptr所有权错误

发布时间:2020-12-16 10:33:48 所属栏目:百科 来源:网络整理
导读:参见英文答案 Returning unique_ptr from functions????????????????????????????????????5个 我是unique_ptr的新手.一切都很顺利,直到我遇到一个函数返回一个新的unique_ptr.编译器似乎抱怨可能拥有unique_ptr的多个对象.我不确定如何满足编译器的投诉.任何
参见英文答案 > Returning unique_ptr from functions????????????????????????????????????5个
我是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 https://stackoverflow.com/questions/4316727/returning-unique-ptr-from-functions
} // this function compiles

解决方法

删除const,当你返回const值时,编译器被迫使用复制构造函数.按const值返回几乎没有意义,强烈建议不要使用.有关更多信息,请参阅 Purpose of returning by const value?.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读