我有这个虚拟方法:
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
是 std::list<std::shared_ptr<base_class>>
, 和 my_class
继承base_class
.但是,在第一次递归调用(my_class::to_string
)之后,在我返回这个 child 之后 str
, 我得到一个错误的分配。
为什么?
最佳答案
正如 BoBTFish 所指出的,您应该将函数签名更改为:
string my_class::to_string() const
因为您是在本地修改字符串,而不仅仅是返回对类成员的引用。否则,您只需返回对本地字符串的引用,即 UB。
关于c++ - 列表分配错误 <shared_ptr>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11329770/