c ++:如何从函数返回shared_ptr

use*_*836 3 c++ return function 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> recipe(new Recipe(recipeName, autherId));

    recipes.push_back(recipe);
    return recipe;
}
Run Code Online (Sandbox Code Playgroud)

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

dlf*_*dlf 8

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