Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is returning address of local variable or temporary only a warning and not an error?

Tags:

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.

like image 275
Robinson Avatar asked Jun 03 '15 11:06

Robinson


People also ask

Why shouldn't we return the address of a local variable from a function?

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.

Is it possible to return the address of a local variable?

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.

How do you return address in C++?

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; };


Video Answer


1 Answers

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.

like image 73
Stefano Sanfilippo Avatar answered Oct 19 '22 12:10

Stefano Sanfilippo