c++ - What's the one liner for assigning a std::shared_ptr from the result of a function? -


there's gotta more idiomatic way this:

potato specialpotato(); std::shared_ptr<potato> givepotato() {     std::shared_ptr<potato> ret;     *ret = specialpotato();     return ret; } 

*ret = specialpotato(); not going work ret null pointer default constructed. if want return std::shared_ptr<potato> points potato value specialpotato() returned can use std::make_shared like

std::shared_ptr<potato> givepotato() {     return std::make_shared<potato>(specialpotato()); } 

this dynamically allocate potato, initialize return of specialpotato() , return shared_ptr.


do note if specialpotato() supposed return type derived potato can't return potato. slice object , you lose derived part of object. when returning derived type parent type need use pointer/pointer-like type like

std::shared_ptr<potato> specialpotato() {     return std::make_shared<specialpotatotype>(/* constructor parameters here */); }    

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -