Private members vs temporary variables in C++
<p>Suppose you have the following code:</p>

<pre><code>int main(int argc, char** argv) {
    Foo f;
    while (true) {
        f.doSomething();
    }
}
</code></pre>

<p>Which of the following two implementations of Foo are preferred?</p>

<p>Solution 1:</p>

<pre><code>class Foo {
    private:
        void doIt(Bar&amp; data);
    public:
        void doSomething() {
            Bar _data;
            doIt(_data);
        }
};
</code></pre>

<p>Solution 2:</p>

<pre><code>class Foo {
    private:
        Bar _data;
        void doIt(Bar&amp; data);
    public:
        void doSomething() {
            doIt(_data);
        }
};
</code></pre>

<p>In plain english: if I have a class with a method that gets called very often, and this method defines a considerable amount of temporary data (either one object of a complex class, or a large number of simple objects), should I declare this data as private members  of the class?</p>

<p>On the one hand, this would save the time spent on constructing, initializing and destructing the data on each call, improving performance. On the other hand, it tramples on the "private member = state of the object" principle, and may make the code harder to understand.</p>

<p>Does the answer depend on the size/complexity of class Bar? What about the number of objects declared? At what point would the benefits outweigh the drawbacks?</p>
