[Bug libstdc++/39416] New: std::map::operator[] inserts a new item in RHS context

2009-03-09 Thread glyn at adgie dot f9 dot co dot uk
#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::mapstd::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



[Bug libstdc++/39416] std::map::operator[] inserts a new item in RHS context

2009-03-09 Thread glyn at adgie dot f9 dot co dot uk


--- Comment #2 from glyn at adgie dot f9 dot co dot uk  2009-03-09 21:25 
---
Thanks Paolo, I suspected that this was not a bug in libstdc++, but
standard-compliant behaviour.

It just seems so unexpected, when compared to other languages that have maps,
e.g. tables in Lua. It is also unexpected when compared to other STL
containers, e.g. std::vector. A bug in the standard, perhaps? I would have
thought that if other languages can implement the expected behaviour for
reading from an associative array, so should C++. Perhaps there is something in
the implementation of std::map that makes this impossible or inefficient, but I
must say, I cannot see why.


-- 


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=39416