Best Way to Return a Class in C++
<p>I'm writing a C++ vector class for a project and I'm having a hard time making a decision about how best to write some of the methods. Before I start I will say that the class has a good copy constructor and assignment operator (this will be relevant in a sec). The class has a set of static methods that return vectors when I want to make sure that neither parameter is altered, they have signatures like:</p>

<pre><code>Vector* Vector::subtract(const Vector* v, const Vector* u)
{
    double outX = v-&gt;myX - u-&gt;myX;
    double outY = v-&gt;myY - u-&gt;myY;
    double outZ = v-&gt;myZ - u-&gt;myZ;

    return new Vector(outX, outY, outZ);
}
</code></pre>

<p>The problem I am having is that I don't want to return pointers if I can help it. So instead I did some testing and realized that if I just say </p>

<pre><code>return Vector(outX, outY, outZ)
</code></pre>

<p>and then assign the result like</p>

<pre><code>Vector foo = Vector::subtract(bar, temp)
</code></pre>

<p>it will create a copy and work fine. Here's where my question lies: I just called the constructor twice (essentially) is there a way to get around that? Secondly, if I use this method as a argument to another method like</p>

<pre><code>foo.multiply(&amp;Vector::subtract(foo, bar), 5)
</code></pre>

<p>will it still create a copy or did I just pass the pointer that has gone out of scope in the Vector::subtract method?</p>

<p>More generally, what is the best (or at least is there a better) way to do this?</p>
