Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat happened when call std::map's operator[] or insert
    text
    copied!<p>I have following code:</p> <pre><code>#include &lt;functional&gt; // std::less #include &lt;map&gt; #include &lt;iostream&gt; using namespace std; class Key { public: Key() {cout &lt;&lt; "Key Constructor" &lt;&lt; endl;} ~Key() {cout &lt;&lt; "Key Destructor" &lt;&lt; endl;} Key(const Key&amp; key) {cout &lt;&lt; "Key Copy Constructor" &lt;&lt; endl;} bool operator &lt; (const Key&amp; k1) {return true;} }; int main() { map&lt;Key, int&gt; mymap; Key k; cout &lt;&lt; "operator[]"&lt;&lt;endl; mymap[k] = 1; map&lt;Key, int&gt; mymap2; cout &lt;&lt; "insert"&lt;&lt;endl; mymap2.insert(std::make_pair(k, 1)); cout &lt;&lt; "=========" &lt;&lt; endl; } </code></pre> <p>And the output is:</p> <pre><code>$ g++ test.cpp -fpermissive $ ./a.out Key Constructor operator[] Key Copy Constructor Key Copy Constructor Key Destructor insert Key Copy Constructor Key Copy Constructor Key Copy Constructor Key Copy Constructor Key Destructor Key Destructor Key Destructor ========= Key Destructor Key Destructor Key Destructor </code></pre> <p>Could anyone please explain why mymap[k] = 1; invoke 2 copy constructor and mymap2.insert(std::make_pair(k, 1)); invokes 4 copy constructor? and does that mean operator[] is much more efficient than insert?</p> <p>Thanks.</p> <p><strong>Summary:</strong></p> <p>Thanks user 6502 and petersohn for your insight, I now guess the reason for the 2 extra copy constructor for insert is as below:</p> <ul> <li><a href="http://www.cplusplus.com/reference/utility/make_pair/?kw=make_pair" rel="nofollow">make_pair</a> is a function, it make a copy inside function first, and then return the copy - that is one extra copy</li> <li>make_pair(k, 1) will create a <code>pair&lt;Key, int&gt;</code>, but the required <a href="http://www.cplusplus.com/reference/map/map/" rel="nofollow">value_type</a> is <code>pair&lt;const&amp; Key, int&gt;</code>, the type conversion will cause another extra copy</li> </ul> <p>So in case 2, if I use:</p> <pre><code>mymap2.insert(std::pair&lt;const Key, int&gt;(k, 1)); </code></pre> <p>The number of copy constructors get called will be the same with operator[]</p> <p>As 6502 noted, following <a href="http://www.cplusplus.com/reference/map/map/operator%5B%5D/" rel="nofollow">claim</a> has been changed hence not true anymore:</p> <blockquote> <p>A call to this function(operator[]) is equivalent to: (*((this->insert(make_pair(x,mapped_type()))).first)).second</p> </blockquote> <p>operator[] is implemented different to avoid extra copy introduced by make_pair()</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload