Boost logo

Boost :

Subject: Re: [boost] ptr_map_adapter::insert non const key argument
From: Gaetano Mendola (mendola_at_[hidden])
Date: 2013-06-21 09:16:10


On 06/20/2013 01:54 PM, Pekka Seppänen wrote:
> On 20.6.2013 14:41, Gaetano Mendola wrote:
>> Hi,
>> it seems that the method:
>>
>> std::pair<iterator,bool> ptr_map_adapter::insert( key_type& key, mapped_type x )
>>
>> has the key argument non const? Is there a valid reason for it or it's just a mistake?
>
> It's a deliberate choice. I'm quoting the pointer container FAQ here..
>
> Q: Why does ptr_map<T>::insert()/replace() take two arguments (the key and the pointer) instead of one std::pair? And why is the key passed by non-const reference?
>
> A: This is the only way the function can be implemented in an exception-safe manner; since the copy-constructor of the key might throw, and since function arguments are not guaranteed to be evaluated from left to right, we need to ensure that evaluating the first argument does not throw. Passing the key as a reference achieves just that.

Back again on this, I believe that Answer can be rephrased, indeed it's a bit cryptic:

A: This is the only way the function can be implemented in an exception-safe manner;
   since the key can be the result of a temporary object result of a function/method call,
   (that can throw an exception) and since function arguments are not guaranteed to be
   evaluated from left to right, we need to ensure that evaluating the first argument does
   not throw. Passing the key as a non-const reference achieves just that.

the argument of the "copy-constructor" can throw is misleading indeed can be seen as:
"the class doesn't make a copy of the key!".

My cent.

Regards
Gaetano Mendola


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk