问题
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 ?
回答1:
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.
来源:https://stackoverflow.com/questions/24440613/c-how-to-return-a-shared-ptr-from-function