Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

You return reference to a local variable. This variable become outdated when function to_string() exits its scope. If you use C++11, you can freely return str by value. The move semantics will be used and no copy will happens.

std::string my_class::to_string() const
{
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top