2012-07-04 44 views
1

壞分配我有這樣的虛方法:與列表<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; 
} 

childrenstd::list<std::shared_ptr<base_class>>my_class繼承base_class。但是,在第一次遞歸調用(my_class::to_string)之後,並且在我返回此子節點str後,我得到一個錯誤的分配。

爲什麼?

+4

你爲什麼要做e.get() - > to_string()而不是e-> to_string()? –

+8

那麼你正在爲初學者返回一個本地變量的引用。 – BoBTFish

+1

將返回類型改爲'string',從'const string&'返回一個對局部變量的引用(正如@BoBTFish所指出的那樣)。 – hmjd

回答

3

正如指出的BoBTFish,你應該函數簽名改爲:

string my_class::to_string() const 

,因爲你是在本地修改字符串,而不僅僅是恢復到一個類成員的引用。否則,您只需返回一個對本地字符串的引用,即UB。

2

您返回對局部變量的引用。當函數to_string()退出其作用域時,該變量將變得過時。如果你使用C++ 11,你可以自由地按值返回str。移動語義將被使用並且不會發生複製。

std::string my_class::to_string() const 
{ 
}