Note that there are some explanatory texts on larger screens.

plurals
  1. POAssign to object being created in c++
    text
    copied!<p>I'm writing some functions to operate on vector data.</p> <p>I defined the objects non-copyable (private copy constructor and assignment operator).</p> <p>Then I defined the templated operator =</p> <pre><code>template &lt;typename G&gt; inline const TMatrix &amp;operator=(const G &amp;gen) { ir_mat::Copy&lt;G, Dimension&gt;::start(m_data, gen); return *this; } </code></pre> <p>and some extra operators, like '+', '*', as described in this <a href="http://www.flipcode.com/archives/Faster_Vector_Math_Using_Templates.shtml" rel="nofollow">article</a>.</p> <p>Now I can assign the result of an expression to an object:</p> <pre><code>Vector3f v1, v2, v3; v1 = v2 + v3; </code></pre> <p>Why can't I declare a variable and assign it in a single statement?</p> <pre><code>Vector3f v1, v2; Vector3f v3 = v1 + v2; </code></pre> <p>Is it because this assignment tries to create a temporary object before instantiating the variable, and then copy it into the new object? Can I use my operator '=' also for instantiating new objects, without temporary storage? Do I have to define a special constructor for that?</p> <p><strong>Update</strong></p> <p>I also defined a templated copy constructor (in its simplest form, probably):</p> <pre><code>template &lt;typename G&gt; TMatrix(const G &amp;data) { operator=(data); } </code></pre> <p>Now I can also instantiate v3 as:</p> <pre><code>Vector3f v3(v1 + v2); </code></pre> <p>But still no luck with the other assignment:</p> <pre><code>Vector3f v3 = v1 + v2; </code></pre>
 

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