views:

87

answers:

1

Stepping through my program in gdb, line 108 returns right back to the calling function, and doesn't call the copy constructor in class A, like (I thought) it should:

template <class S> class A{
    //etc...
    A( const A & old ){
        //do stuff...
    }
    //etc...
};

template <class T> class B{
    //etc...
    A<T> ReturnsAnA(){
        A<T> result;
        // do some stuff with result
        return result; //line 108
    }
    //etc...
};

Any hints? I've banged my head against the wall about this for 4 hours now, and can't seem to come up with what's happening here.

+1  A: 

(Named) return value optimization is in effect. Your copy constructor is being removed as an optimization (this is permitted by the standard although results in different behavior).

See also http://stackoverflow.com/questions/1394229/understanding-return-value-optimization-and-returning-temporaries-c.

(Templates have nothing to do with this.)

KennyTM