简体   繁体   中英

Bad allocation with list<shared_ptr>

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.

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
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM