2014-02-18 46 views
2

我正在查找std::map中的密钥值。我碰到下面的错误数据集::的getProperty()内:std :: map :: at返回警告“返回引用临时”在调用栈的某处

returning reference to temporary [-Wreturn-local-addr]

凡在调用堆栈是临时产生的?我认为std::map::at返回了一个左值的引用,并且因为我不断返回reference-to-const原始调用者将有一个左值的引用。

数据集

class Dataset 
{ 
    private: 
    PropertyCollection properties; 

    public: 
    const std::string & getProperty(const std::string & key) const; 

    ... 
} 

const std::string & Dataset::getProperty(const std::string & key) const 
{ 
    // WARNING: returning reference to temporary [-Wreturn-local-addr] 
    return properties.getProperty(key); 
} 

PropertyCollection

class PropertyCollection 
{ 
    private: 
    std::map<std::string, std::string> properties; 

    public: 
    const bmd2::string & getProperty(const bmd2::string & key) const 

    ... 
} 

const std::string & PropertyCollection::getProperty(const std::string & key) 
     const 
{ 
    try { 
    return properties.at(key); 
    } catch (std::out_of_range & e) { 
    ... 
    } 

int main() { 
    ... 
    std::string key ("Cats"); 
    std::string value = dataset.getProperty(key); 
} 

回答

10

getProperty返回bmd2::string而不是std::string。因此std::string必须隐含地构造/从bmd2::string转换。这std::string当然是一个新的临时对象。

虽然它实际上不是非法的返回引用临时,使用这样的引用(如果超出范围)将导致UB,因此编译器警告你。

+1

假设是'bmd2 :: string'和'std :: string'不是同一类型,我想。 –

+0

啊,隐式转换!是的,它们不是同一类型。感谢你抓住这个Paranaix。 –

相关问题