So.. I was writing some code and wanted to know the prototype for a compound operator (i.e. something like operator*= or operator/=). When I looked it up I realized that they're supposed to return references. (Or at least my source indicated as such: R& operator +=(K& a, S b); .) Well.. I then realized that a line in my code might be a little more dangerous than it appeared to be:
// I have a really fancy Vector class I've been making. :P
template<typename T, int N>
inline Vector<T, N>& Vector<T, N>::operator*(const Vector<T, N>& vec, T scale) {
Vector<T, N> ret {};
return ret *= scale;
}
So.. I was wondering if this is harmless... or will cause a reference to a local variable to leak out and cause all kinds of undefined behavior and general havoc. (I'm leaning towards havoc, and, as such, rewrote it as below. :P )
// I have a really fancy Vector class I've been making. :P
template<typename T, int N>
inline Vector<T, N>& Vector<T, N>::operator*(const Vector<T, N>& vec, T scale) {
Vector<T, N> ret {};
ret *= scale;
return ret;
}
So.. yea.. general C++ "what if?" question here. Would be nice to know for sure. (And I was too lazy to try and make a test case and see if my program halted and caught fire. :P )
Aucun commentaire:
Enregistrer un commentaire