壞分配我有這樣的虛方法:與列表<shared_ptr>
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
)之後,並且在我返回此子節點str
後,我得到一個錯誤的分配。
爲什麼?
你爲什麼要做e.get() - > to_string()而不是e-> to_string()? –
那麼你正在爲初學者返回一個本地變量的引用。 – BoBTFish
將返回類型改爲'string',從'const string&'返回一個對局部變量的引用(正如@BoBTFish所指出的那樣)。 – hmjd