#include <iostream> #include <map> #include <string> // Demonstrate unexpected behaviour of std::map::operator[] when used in a read // context, e.g. on the right hand side of an assignment. // // The intended application is a shell environment table, where accessing a // non-existent variable should yield an empty string, but not alter the table. // In my shell, I sometimes wish to distinguish between an existing variable // with an empty value, and a non-existent variable. The behaviour of // std::map::operator[] defeats this, so I have to use the more verbose // std::map::find interface for reading from the map.
int main(int argc, char * argv[]) { typedef std::map<std::string, std::string> env_type; env_type env; env["my_var"] = "Hello world!"; // Add an item. std::cout << env["thing"] << std::endl; // Empty string, as expected. // List all variables and their values. for(env_type::const_iterator it = env.begin(); it != env.end(); ++it) { std::cout << it->first << '=' << it->second << std::endl; } // Oh no! The non-existent variable 'thing' has been added to the map. // // my_var=Hello world! // thing= return 0; } -- Summary: std::map::operator[] inserts a new item in RHS context Product: gcc Version: 4.3.3 Status: UNCONFIRMED Severity: normal Priority: P3 Component: libstdc++ AssignedTo: unassigned at gcc dot gnu dot org ReportedBy: glyn at adgie dot f9 dot co dot uk http://gcc.gnu.org/bugzilla/show_bug.cgi?id=39416