为什么返回局部变量或临时地址只是警告而不是错误? [英] Why is returning address of local variable or temporary only a warning and not an error?

查看:246
本文介绍了为什么返回局部变量或临时地址只是警告而不是错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚从编译器收到此功能的警告:

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?

我想不出什么。

推荐答案

没有充分的理由说明它应该不是错误,只是 C ++标准不会这样处理,并且符合标准的编译器也遵守该标准。

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.

但是,鼓励发出警告:


§12.2.5.2在函数return语句(6.6.3)中,与返回值临时绑定的生存期不会延长; 临时变量在return语句中的完整表达式结束时被销毁。

§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 ]

强调是我的。

这篇关于为什么返回局部变量或临时地址只是警告而不是错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆