Having just received a warning from the compiler for this function:
template<class T> Matrix3x3<T> & operator - (Matrix3x3<T> const & p) { auto m = Matrix3x3<T>(p); m.m11 = -m.m11; m.m12 = -m.m12; m.m13 = -m.m13; m.m21 = -m.m21; m.m22 = -m.m22; m.m23 = -m.m23; m.m31 = -m.m31; m.m32 = -m.m32; m.m33 = -m.m33; return m; }
, I am wondering why returning an address of local variable or temporary doesn't merit an error. Are there circumstances where you have to do it? What's the rationale for this only being "undefined behaviour" and not a language constraint?
I can't think of any.
The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.
a is an array local to the function. Once the function returns it does not exist anymore and hence you should not return the address of a local variable.
If you want to return a pointer you should use a pointer: node* create_node(int value) { node *newitem = new node; newitem->data = value; newitem->next = NULL; return newitem; };
There is no good reason why it shouldn't be an error, just the C++ standard does not treat this case as such and conforming compilers adhere to the standard.
However, emitting a warning is encouraged:
§12.2.5.2 The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
[...]
[Note: This may introduce a dangling reference, and implementations are encouraged to issue a warning in such a case. — end note ]
Emphasis is mine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With