c++ - Returning a new instance of a class -
this question has answer here:
- how “return object” in c++? 7 answers
i thinking semantics of returning class type.
consider simple vector class.
#ifndef __vector_h__ #define __vector_h__ #include <cmath> class vector2f { public: float x; float y; vector2f() : x(0), y(0) {} vector2f(int x,int y) : x((float)x), y((float)y) {} vector2f(float x, float y) : x(x), y(y) {} ~vector2f() {} float length() { return pow( float(x*x + y*y) , 0.5 ); } void unit() { //instead of making current vector unit vector //i return unit vector float len = length(); if(len != 1.0) { x = x / len; y = y / len; } return; } }; #endif
the function unit() makes current vector unit vector, thinking instead return unit vector new unit vector (i may not want lose old 1 instance).
i started thinking becomes memory management nightmare because anytime unit() called, allocate memory , later have deleted. seems dumb way it.
vector2f unit() { float len = length(); return new vector2f(x/len,y/len); }
is there better way this? considered maybe having function demand reference vector2f object.
the payload vector2f decidedly small: 2 x float members. it's not worth allocating them on heap. instead consider capturing type reference or const reference function parameters , returning value.
the unit function be:
vector2f unit() { float len = length(); return vector2f(x/len,y/len); }
Comments
Post a Comment