I have a std::unordered_map<int, std::string>
and a function GetString(int key)
that takes an int key and returns a string value from this map.
When the key isn't found in the map, I have to return an empty string.
#include <iostream>
#include <string>
#include <unordered_map>
std::unordered_map<int, std::string> map
{
{ 5, "somelongstring" }
};
const std::string& GetString(int key)
{
auto iterator = map.find(key);
if (iterator == map.end())
{
return "";
}
return iterator->second;
}
int main()
{
std::cout << GetString(1) << std::endl;
}
The problem is the compiler gives me this warning
warning C4172: returning address of local variable or temporary
(with MS Visual Studio 2013) or
warning: returning reference to temporary [-Wreturn-local-addr]
(with g++ 4.9.2)
One way to get out of this I found was to declare a static const std::string
at the top and return that instead of the empty string literal
static const std::string Empty = "";
const std::string& GetString(int key)
{
auto iterator = map.find(key);
if (iterator == map.end())
{
return Empty;
}
return iterator->second;
}
But it didn't seem very clean to define an empty string literal. Is there a neat way to do this?
Update: My map is initialized once during startup and then read simultaneously from multiple threads (using GetString
). Using a function static empty string wouldn't work because function static variables aren't initialized in a thread safe manner under visual studio's compiler.