c++ - Should a function return a "new" object -


should function return pointer memory allocated on heap?

in other words, of following methods more "correct"?

// method #1 object* getobject1() {     return new object(); }  // method #2 std::shared_ptr<object> getobject2() {     return std::make_shared<object>(); }  int main() {     // usage of method #1     object* o1 = getobject1();     o1->dosomething();     delete o1; // object has deleted user      // usage of method #2     std::shared_ptr<object>& o2 getobject2(); // has kept in shared_ptr     o2.get()->dosomething();     // object deleted when o2 destructs } 

i imagine first method faster, second method not require user delete object.

of two, second preferred. naked pointers should last choice. ideally, return object value. failing that, unique_ptr better shared_ptr unless need shared ownership.

i imagine first method faster.

that's true shared_ptr. unique_ptr, compiler can optimize. there's no benefit pays risk of manual deletion.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -