Reputation:
I am looking up the value of a key from a std::map
. I get the following error inside Dataset::getProperty():
returning reference to temporary [-Wreturn-local-addr]
Where in the call stack is the temporary created? I thought std::map::at
returned a reference to an lvalue, and because I continously return reference-to-const
that the original caller would have a reference to the lvalue.
Dataset
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) {
...
}
Main
int main() {
...
std::string key ("Cats");
std::string value = dataset.getProperty(key);
}
Upvotes: 2
Views: 661
Reputation: 11502
getProperty
returns a bmd2::string
not a std::string
. Thus a std::string
must be implicitely constructed/converted from a bmd2::string
. This std::string
is then of course a new temporary object.
While its actually not illegal to return a reference to a temporary, using such a reference (if out of scope) will result in UB, thus the compiler warns you.
Upvotes: 10