c ++:如何从函数返回一个shared_ptr [英] c++: how to return a shared_ptr from function

查看:543
本文介绍了c ++:如何从函数返回一个shared_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图从函数返回一个shared_ptr时,我得到:
引用局部变量'recipe'返回[-Werror = return-local-addr]



<我哪里错了?

  shared_ptr< Recipe>& Group :: addRecipe(const string& groupName,unsigned int autherId,const string& recipeName){

shared_ptr< Recipe>食谱(新食谱(recipeName,autherId));

recipes.push_back(recipe);
返回食谱;
}

返回shared_ptr的正确方法是什么?

解决方案

函数的签名没有显示,但它听起来像可能返回 shared_ptr< Recipe>& 。将引用返回给临时对象是一个很大的禁忌,因为一旦函数退出,被引用的对象就会被销毁。只需返回值。


when trying to return a shared_ptr from a function I get: reference to local variable 'recipe' returned [-Werror=return-local-addr]

where did I go wrong ?

shared_ptr<Recipe>& Group::addRecipe(const string& groupName, unsigned int autherId, const string& recipeName){

    shared_ptr<Recipe> recipe(new Recipe(recipeName, autherId));

    recipes.push_back(recipe);
    return recipe;
}

what is the right way to return a shared_ptr ?

解决方案

The function's signature isn't shown, but it sounds like it's probably returning shared_ptr<Recipe>&. Returning a reference to a temporary is a big no-no since the referenced object will be destroyed as soon as the function exits. Just return by value instead.

这篇关于c ++:如何从函数返回一个shared_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆