c++: how to return a shared_ptr from function

心已入冬 提交于 2019-12-22 10:21:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!