Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The core difference is that they are different unrelated types (with some implicit conversions among them).</p> <pre><code>void f(std::pair&lt;std::string,std::string&gt; const &amp;); std::string longstring(); int main() { std::pair&lt;const std::string,const std::string&gt; pc = std::make_pair(longstring(),longstring()); f(pc); const std::pair&lt;std::string,std::string&gt; cp = std::make_pair(longstring(),longstring()); f(cp); } </code></pre> <p>While there are implicit conversions that allow <code>f(pc)</code> to compile, that line involves a <em>conversion</em>, and the conversion involves making a <em>copy</em> of the <code>longstring()</code>s. On the other hand, the call <code>f(cp)</code> only binds a constant reference to the existing pair as the type matches, not requiring any copies.</p> <p>The fact that the compiler let's you write similar code, does not mean that the code is compiled to do the same thing. This is particularly true for types with implicit conversions, as is the case of <code>std::pair</code></p> <p>This is a common pitfall when writing functors to operate on elements stored in maps, where a mismatch on the argument of the functor will cause unnecessary copying of the object data:</p> <pre><code>std::map&lt;int,std::string&gt; m = create_map(); std::for_each(m.begin(),m.end(), [](std::pair&lt;int,std::string&gt; const &amp;r) { std::cout &lt;&lt; r.second &lt;&lt; " "; }); </code></pre> <p>The lambda above does not have the correct type of argument (<code>std::pair&lt;int,std::string</code> vs. <code>std::pair&lt;const int,std::string&gt;</code>) and that causes each call to copy both the index and the value (i.e. all strings will be copied, to an <code>std::pair&lt;int,std::string&gt;</code> and then a reference bound for the argument to the lambda). The simple recommendation in this case would be to use <code>std::map&lt;int,std::string&gt;::value_type const &amp;</code> for the argument type.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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