1

我有这个虚拟方法:

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

哪里children是 a std::list<std::shared_ptr<base_class>>,并my_class继承base_class。但是,在第一次递归调用 (of my_class::to_string) 之后,在我返回这个 child 之后str,我得到了一个错误的分配。

为什么?

4

2 回答 2

3

正如 BoBTFish 所指出的,您应该将函数签名更改为:

string my_class::to_string() const

因为您正在本地修改字符串,而不仅仅是返回对类成员的引用。否则,您只需返回对本地字符串的引用,即 UB。

于 2012-07-04T13:17:35.540 回答
2

您返回对局部变量的引用。当函数 to_string() 退出其范围时,此变量会过时。如果你使用 C++11,你可以自由地按值返回 str。将使用移动语义并且不会发生复制。

std::string my_class::to_string() const
{
}
于 2012-07-04T13:20:19.737 回答