Reputation: 749
I have this code, I want to fill my vector of strings from another class
class A
{
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 this doesnt work because tmp gets destructed, but I dont know how to fix it, should i return pointer to tmp in foo()?
Upvotes: 2
Views: 88
Reputation: 254751
I know this doesnt work because tmp gets destructed
It's destroyed after it's copied to give the function's return value, so there's no problem there. There would be a problem if you returned a pointer or reference to the local variable; but you're not doing that.
I dont know how to fix it
It's not broken, so there's nothing to fix.
should i return pointer to
tmp
No, that would introduce exactly the problem you're thinking of. Returning by value avoids the problem.
Upvotes: 3