当尝试从函数返回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;
}
返回shared_ptr的正确方法是什么?
该函数的签名未显示,但听起来它可能正在返回shared_ptr<Recipe>&
。返回对临时对象的引用是一个很大的禁忌,因为一旦函数退出,引用的对象就会被销毁。只需按值返回即可。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)