I have this virtual method:
const string& my_class::to_string() const
{
string str(this->name + string(" "));
if(!this->children.empty())
{
for(const std::shared_ptr<base_class> e : this->children)
str.append(e.get()->to_string());
}
return str;
}
Where children
is a std::list<std::shared_ptr<base_class>>
, and my_class
inherits base_class
. But, after the first recursive call (of my_class::to_string
), and after I return this child str
, i get a bad allocation.
Why?
As pointed by BoBTFish, you should change the function signature to:
string my_class::to_string() const
since you are modifying the string locally, and not just returning a reference to a class member. Otherwise you simply return a reference to a local string, which is UB.