Erik Wikström
9/24/2008 5:52:00 PM
On 2008-09-24 19:10, bingo wrote:
> Hi, All:
> I was really new to C++, so please forgive me if I asked stupid
> questions.
>
> I was trying to use this following Vector class(not written by me)
> to do some calculations :
>
> =============================================
> class Vector {
> public:
> double x,y,z;
>
> inline Vector(void) : x(-99999), y(-99999), z(-99999) { ; }
> // inline Vector(void) { ; }
>
> inline Vector( double newx, double newy, double newz)
> : x(newx), y(newy), z(newz) { ; }
>
> inline Vector( double newv ) // allow Vector v = 0; etc.
> : x(newv), y(newv), z(newv) { ; }
>
> inline Vector(const FloatVector &v) : x(v.x), y(v.y), z(v.z)
> { ; }
>
> inline double operator[](int i) {
> return i==0 ? x
> :i==1 ? y
> :i==2 ? z
> : x;
>
> }
>
> // v1 = v2
> inline Vector& operator=(const Vector &v2) {
> x = v2.x;
> y = v2.y;
> z = v2.z;
> return *this;
> }
>
> // v1 = const;
> inline Vector& operator=(const double &v2) {
> x = v2;
> y = v2;
> z = v2;
> return *this;
> }
>
> // addition of two vectors
> inline friend Vector operator+(const Vector& v1, const Vector&
> v2) {
> return Vector( v1.x+v2.x, v1.y+v2.y, v1.z+v2.z);
> }
>
> // negation
> inline friend Vector operator-(const Vector &v1) {
> return Vector( -v1.x, -v1.y, -v1.z);
> }
>
> // subtraction
> inline friend Vector operator-(const Vector &v1, const Vector
> &v2) {
> return Vector( v1.x-v2.x, v1.y-v2.y, v1.z-v2.z);
> }
>
> // inner ("dot") product
> inline friend double operator*(const Vector &v1, const Vector
> &v2) {
> return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
> }
> // scalar product
> inline friend Vector operator*(const double &f, const Vector &v1)
> {
> return Vector(f*v1.x, f*v1.y, f*v1.z);
> }
> // scalar product
> inline friend Vector operator*(const Vector &v1, const double &f)
> {
> return Vector(f*v1.x, f*v1.y, f*v1.z);
> }
> // division by a scalar
> inline friend Vector operator/(const Vector &v1, const double &f)
> {
> return Vector(v1.x/f, v1.y/f, v1.z/f);
> }
>
> };
>
> ==========================
>
> My main code looks like this :
>
> int main () {
>
> Vector a, b, c, d;
> a = b + c - d;
> a = b * 5.0;
>
> }
>
> Now my question is : for the operation - and + and scalar product,
> will it return a new Vector and not be released during my calculation,
> which finally leads to memory leak? If so, how can I fix this problem?
No, the +, -, and scalar product will return Vector-objects, these will
be temporary objects which will die at the end of the expression they
are part of. As a general rule you can not leak memory unless you
allocate it first, which is usually done using 'new', which is not used
in your code.
--
Erik Wikström