c++ - Return class instance from class -


i have code, want fill vector of strings class

class {   public:     b foo(const string & name) const; }  class b {   public:     void add(const string & name);     vector<string> list; }  void b::add(const string & name) {    list.push_back(name); }  b a::foo(const string & name) const {   b tmp;   tmp.add(name);   return tmp; } 

i know doesnt work because tmp gets destructed, dont know how fix it, should return pointer tmp in foo()?

i know doesnt work because tmp gets destructed

it's destroyed after it's copied give function's return value, there's no problem there. there problem if returned pointer or reference local variable; you're not doing that.

i dont know how fix it

it's not broken, there's nothing fix.

should return pointer tmp

no, introduce problem you're thinking of. returning value avoids problem.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -