1

So I've been writing a small math library in C++ and when dealing with a scalar multiplied by a vector I get some issues when I try to perform this operation

Vect V2;
Vect V3;
float S;

Vect V1 = V2 + S * (V2 - V3);

The Vect Value I receive in the overloaded operator * is a new Vect object and not the outcome of the (V2 - V3) part of the operation. Here's the other relevant part of the code. If I follow the operation with the debugging the two overloaded operators work correctly by themselves but not one after the other.

Vect.h

Vect &operator - (const Vect &inVect);
friend const Vect operator*(const float scale, const Vect &inVect);

Vect.cpp

Vect &Vect::operator - (const Vect &inVect)
{
    return Vect (this->x - inVect.x,this->y - inVect.y,this->z - inVect.z, 1);
}

const Vect operator*(const float scale, const Vect &inVect)
{
    Vect result;

    result.x = InVect.x * scale;
    result.z = InVect.y * scale;
    result.y = InVect.z * scale;
    result.w = 1;

    return result;
}

I also overloaded the + and = operator and they work as expected the only problem I encounter is the problem above.

4

1 回答 1

5

在您的operator-中,您创建一个临时Vect文件并返回对该临时文件的引用。临时对象在语句结束时被销毁,return返回的引用悬空。对这个引用做任何事情都会导致未定义的行为。

相反,您operator-应该Vect按值返回:

Vect Vect::operator - (const Vect &inVect)
{
  return Vect (this->x - inVect.x,this->y - inVect.y,this->z - inVect.z, 1);
}
于 2013-02-09T12:42:31.257 回答