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);
}
假设是'bmd2 :: string'和'std :: string'不是同一类型,我想。 –
啊,隐式转换!是的,它们不是同一类型。感谢你抓住这个Paranaix。 –