Deutsch   English   Français   Italiano  
<vhlha1$8p1l$1@dont-email.me>

View for Bookmarking (what is this?)
Look up another Usenet article

Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: Andrey Tarasevich <andreytarasevich@hotmail.com>
Newsgroups: comp.lang.c++
Subject: Re: std::map::emplace useful in any way?
Date: Sun, 30 Jun 2024 13:32:00 -0700
Organization: A noiseless patient Spider
Lines: 35
Message-ID: <v5sfc1$lv3d$1@dont-email.me>
References: <v2t1pv$1bdc2$1@gwaiyur.mb-net.net>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Date: Sun, 30 Jun 2024 22:32:02 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="b08812f99415a44bc83c17970a63b04e";
	logging-data="719981"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX1/z//UDUny/tRZaV2W7JZ3k"
User-Agent: Mozilla Thunderbird
Cancel-Lock: sha1:gQh7vC3f54DOh5AzqKHOrA9xUkA=
In-Reply-To: <v2t1pv$1bdc2$1@gwaiyur.mb-net.net>
Content-Language: en-US
Bytes: 2628

On 05/25/24 8:57 AM, Marcel Mueller wrote:
> The emplace functions generally allows to construct container objects
> directly at the target location. But std::map expects a value type of
> std::pair<const Key, T>. Now the implementation of emplace needs to
> instantiate the value type just to get the key to find the insert
> location. This cannot happen at the target location, isn't it?

Yes, it sorta-kinda can happen "at target location", If I correctly 
understand what you mean by "target location".

In mainstream implementations `emplace` does not really construct a some 
local `value_type t` object. Instead, it immediately allocates and 
constructs out of the supplied arguments a _node_ object. This node 
object is what the `std::map` is literally built of and, of course, that 
node object contains a `value_type` object inside.

If the key is not present in the map, the node object is immediately 
_attached_ directly into to the map. Otherwise, it is destroyed and 
deallocated. In other words, that node object is the "target location".

So, yes, there is an "optimistic" construction of a `value_type` object 
(which might prove to be a waste), but there's no subsequent 
copying/moving from that `value_type` object to the "target location". 
The `value_type` object is created as part of the "target location" from 
the very beginning.

This approach is what permits usage of `emplace` for insertion of 
non-copyable/non-movable objects into the map through 
`std::piecewise_construct` (which is likely what Stefan refers to in his 
comment).

-- 
Best regards,
Andrey