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

5

尝试从函数返回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的正确方式?


6
听起来你的函数可能是返回 shared_ptr& 而不是 shared_ptr。只需改为返回值即可。 - dlf
是的,请显示函数声明。 - grisha
2
请发布一个最小化、完整化和可验证的示例,以便重现错误。 - Csq
你是在问什么是“返回本地变量的引用”吗?那就是你的错误。你不能返回一个指向本地变量的引用。 - Drew Dormann
问题是声明开头的 "&" 吗? - user3776836
@user3776836 看起来你不确定什么是 C++ 引用。这样说对吗? - Drew Dormann
1个回答

8

虽然没有显示函数签名,但听起来它很可能是返回shared_ptr<Recipe>&。返回临时引用是不可取的,因为引用的对象将在函数退出后被销毁。请改为按值返回。


shared_ptr<Recipe>& Group::addRecipe(const string& groupName, unsigned int autherId, const string& recipeName){ 这是函数签名,我刚入门,请问“按值传递”是什么意思?我该怎么做? - user3776836
1
@user3776836请编辑问题以包含额外的信息。 - Csq
@user3776836 在 shared_ptr<Recipe> 后面删除 && 返回一个引用,使得返回值引用了一个不存在的对象。没有 &,你可以返回一个实际的 shared_ptr<Recipe> 值。 - nwp
在这种情况下,返回值只是意味着去掉 &。完整的讨论会很长,但应该有几个关于这个主题的问题。 - dlf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接