I’ve a incertitude about std::map on c++:
I did a Object C_Configuration that loads a linked library (.so) C_ConfigurationLibrary.
The C_Configuration class has a std::map and The C_ConfigurationLibrary has a method that initializes the std::map.
If I access to the std::map from C_Configuration with a “for” loop:
std::map<const char*, const char*>::iterator l_item;
for(l_item = m_configuration_map.begin();
l_item != m_configuration.end();
l_item++)
This is OK;
But if I use :
m_configuration[VALUE_KEY] // the value is NULL
This is not OK;
My CODE:
C_Configuration::C_Configuration()
{
m_configuration = LoadLibrary(); // load the linked library (.so)
if(m_configuration != NULL)
{
// DEBUG
LOG_DEBUG("Loading Key from plugin...");
m_configuration->LoadKeys(m_configuration_map);
std::map <const char*, const char*>::iterator l_item;
for ( l_item = l_configuration_map.begin();
l_item != l_configuration_map.end();
l_item++ )
{
//THIS IS OK
}
m_configuration_map[FIRST_KEY] // THIS IS NOT OK
}
}
void C_ConfigLibrary::LoadKeys(std::map<const char*, const char*>& p_configuration_map)
{
// DEBUG
LOG_DEBUG("Loading Keys...");
p_configuration_map.insert ( std::make_pair<const char*, const char*>(FIRST_KEY, FIRST_VALUE) );
// DEBUG
LOG_DEBUG("Loaded Key DBUS used: %s",m_dbus_used.c_str());
p_configuration_map.insert ( std::make_pair<const char*, const char*>(SECOND_KEY,SECOND_VALUE) );
}
Can you help me?
thanks so much
You’re using
const char*s as keys, but pointers are compared on their memory addresses and not the text to which they point. Consequently, when you have a string literal in the shared library, and the same text in a string literal in the main app object, they can have different addresses and will not compare equal as keys.You’re much better off using
std::strings as the keys, although it’s safe to useconst char*as the values.FWIW, if you use
const char*as a key, not only are string literals from different translation units sometimes finicky like this, but you’ll have difficultly using text from local buffers, evenstd::string‘s.c_str()return values – it’s just a very bad idea.