Avoiding Temporary Variable in Subscript Operator

93 views Asked by At

I have a class v which dynamically allocates an array of doubles. Entries is a pointer to the beginning of this array. Spacing allows me to skip over entries, for example, if I wanted to only consider every third entry, spacing would be 3.

double& v::operator[] (const int n) {
    return entries[n*spacing]; 
}

This subscript operator compiles but causes heap corruption. Based on my web searches, I think Visual Studio is storing the result of "entries[n*spacing]" in a temporary, and then returning a reference to the temporary. Heap corruption occurs when I try to write to this reference to deallocated memory.

Does anyone have ideas for a workaround?

1

There are 1 answers

1
K-ballo On

I think Visual Studio is storing the result of "entries[n*spacing]" in a temporary, and then returning a reference to the temporary.

That is incorrect. Assuming entries is defined as double entries[]; or double* entries, then entries[i] returns a reference and is that reference that gets returned by your subscript operator.

The source of your problem is somewhere else. Perhaps in n*spacing being outside the array bounds, or the whole entries being deallocated by the time the reference is accessed.