Constructor Optimization

Zack Rusin kde-optimize@mail.kde.org
Tue, 21 Jan 2003 11:42:00 -0500


On Tuesday 21 January 2003 10:47, Benjamin Meyer wrote:
> I was curius if GCC/G++ would optimize foo = x down to foo(x) if the
> constructor existed so I wrote a small program to time the two.  Now
> of course the time savings couldn't be much, but a wide scale
> fix/change could probably help, especially in applications that
> constently generate/remove new variables.
<snip>
> Is this wrong?

Yes. For a couple of reasons. The time measurements you did are pretty 
much useless, nothing accurate will come of them. I'd suggest writting 
a lot simpler testcase like:

class Copy {
public:
    Copy( int i = 0 ): mI(i) { cerr<<"\tNormal Constructor"<<endl; }
    Copy( const Copy& c ) { mI = c.getI(); 
                                     cerr<<"\tCopy Constructor"<<endl; }
    int  getI() const { return mI; }
    void setI( int i ) { mI = i; }

    void operator=( const Copy &c ) { mI = c.getI();
                                 cerr<<"\toperator="<<endl; }
private:
	int mI;
};

This will show that gcc in fact always calls copy constructors when 
initializing objects (that is while the signature of one of the copy 
constructors is compatible with operator=)

Zack

-- 
A bash poem: time for echo in canyon; do echo $echo $echo; done