Question

I've got a function to normalize a Vec2D. I recieve both C4172 and C4239 errors. I understand that I should not return local variables, but I don't understand what I should return instead. Should I make it a pointer?
Method:

inline Vec2D& normalize()const {
    double l = length();
    if (x == 0) {
        if (y == 0) {
            return Vec2D(0, 0);
        }
        else {
            return Vec2D(0, y / l);
        }
    }
    else if (y == 0) {
        return Vec2D(x / l, 0);
    }
    return Vec2D(x / l, y / l);
}
Was it helpful?

Solution

It's fine to return local variables, by value. What you should not do, is return them by reference. Drop the & from the return type.

inline Vec2D normalize()const {
    ...

OTHER TIPS

I would probably implement it as:

inline void normalize(Vec2D* vect) const {
    ....

like this, the user of the function could provide a Vec2D from the stack, from the heap, and even a derived class with base Vect2D. Performance is good because no copying is involved.

What you have here is an attempt to return a reference to a temporary object (which is also local) - Vec2D returns an object to your function, but you're not storing it anywhere, just returning a reference to it, which becomes dangling once you move to the next instruction in the code. While in this case the effect is similar to returning a reference to a local variable, it's important to understand the difference. Local variable will become invalid on exit from function and temporary variable will become invalid on the next instruction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top