Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: how to return a shared_ptr from function

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 ?

like image 560
user3776836 Avatar asked Feb 13 '23 15:02

user3776836


1 Answers

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.

like image 83
dlf Avatar answered Feb 20 '23 02:02

dlf