2014-06-26 26 views
1

返回一個shared_ptr試圖從一個函數返回一個shared_ptr當我得到: 引用局部變量「配方」返回[-Werror =返回本地地址]C++:如何從功能

放哪兒我出錯 ?

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

+0

是的,顯示函數聲明,請 – grisha

+2

請發佈一個[最小的,完整的和可驗證的例子](http://stackoverflow.com/help/mcve)來重現錯誤。 – Csq

回答

8

函數的簽名沒有顯示,但它聽起來像可能返回shared_ptr<Recipe>&。將引用返回給臨時對象是一個很大的禁忌,因爲一旦函數退出,被引用的對象就會被銷燬。只需返回值。

+0

shared_ptr &Group :: addRecipe(const string&groupName,unsigned int autherId,const string&recipeName){ 這是簽名,我是新的,這是什麼意思,「按價值」?我怎麼做? – user3776836

+1

@ user3776836請編輯該問題以包含附加信息。 – Csq

+0

@ user3776836在'shared_ptr '後刪除'&'。 '&'返回一個引用,使返回值引用一個不存在的對象。如果沒有'&',則返回實際的'shared_ptr '值。 – nwp