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

一曲冷凌霜 提交于 2019-12-23 06:48:56

问题


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.


回答1:


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.




回答2:


Reason: Lack of consistency in generating compiler error.

In your straight forward case, compiler is actually helpful to generate a warning. Treat it just as a bonus.
But look for below case where compiler doesn't recognize this problem:

int& foo ()
{
  int i = 1;
  static int j;
  return i? i : j;  // No warning in g++-5!
}

Now from the compiler perspective it's not justified if it gives error for one case and in other case it chickens out due to complexity of the code.

One of the use cases of such compiler limitation can be "Random Number generation" as nicely suggested by @tsuki.



来源:https://stackoverflow.com/questions/30618783/why-is-returning-address-of-local-variable-or-temporary-only-a-warning-and-not-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!