Note that there are some explanatory texts on larger screens.

plurals
  1. POMove semantics & returning const values
    text
    copied!<p>I have the habit (?!?!?) of returning everything as a "const" value. Like this...</p> <pre><code>struct s; s const make_s(); s const &amp;s0 = make_s(); s const s1 = make_s(); </code></pre> <p>With move operations and r-value references and the following functions...</p> <pre><code>void take_s(s &amp;&amp;s0); void take_s(s const &amp;&amp;s0); // Doesn't make sense </code></pre> <p>I can no longer write...</p> <pre><code>take_s(make_s()); </code></pre> <p>The main reason I started using the convention of returning const values is to prevent someone from writing code like this...</p> <pre><code>make_s().mutating_member_function(); </code></pre> <p>The use case is the following...</p> <pre><code>struct c_str_proxy { std::string m_s; c_str_proxy(std::string &amp;&amp;s) : m_s(std::move(s)) { } }; c_str_proxy c_str(std::string &amp;&amp;s) { return c_str_proxy(s); } char const * const c_str(std::string const &amp;s) { return s.c_str(); } std::vector &lt; std::string &gt; const &amp;v = make_v(); std::puts(c_str(boost::join(v, ", "))); std::string const my_join(std::vector &lt; std::string &gt; const &amp;v, char const *sep); // THE FOLLOWING WORKS, BUT I THINK THAT IS ACCIDENTAL // IT CALLS // // c_str(std::string const &amp;); // // BUT I THINK THE TEMPORARY RETURNED BY // // my_join(v, "; ") // // IS NO LONGER ALIVE BY THE TIME WE ARE INSIDE // // std::puts // // AS WE ARE TAKING THE "c_str()" OF A TEMPORARY "std::string" // std::puts(c_str(my_join(v, "; "))); </code></pre> <p>Looks as if "returning const value" and r-value references don't mix in this particular use case. Is that right?</p> <pre><code>**Edit 0: Extra question...** </code></pre> <p>The object is temporary anyway. Why should "const" prevent moving? Why can't we move "const" temporaries?</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