返回对局部变量的引用为什么在这种情况下有效?

huangapple go评论68阅读模式
英文:

Why does returning a reference to a local variable work in this case?

问题

以下是翻译的部分:

"我知道有很多类似的问题,但我找不到适合我的确切情况(操作符重载,通过复制传递)的答案。

据我所知,返回对局部变量的引用然后使用它应该导致未定义的行为。但在我的情况下似乎可以工作。这是否只是未定义行为有时也可以工作的情况,还是我忽视了某些事情?

// complex.cc
Complex& operator/(Complex lhs, const Complex& rhs)
{
    return lhs /= rhs;
}
// 在main函数内部
complex::Complex a{3, -6};
complex::Complex b{1, -5};
complex::Complex res{a / b};
std::cout << a << '\n' << b << '\n' << res << std::endl;

我理解,当我将其传递给重载的运算符时,应该创建a的一个副本,然后返回对修改后副本的引用。我的理解是否错误,或者为什么在打印时可以工作?"

英文:

I know there are a ton of questions asking something similar, but I couldn't find anything for my exact situation (operator overload, pass by copy).

As far as I know, returning a reference to a local variable and then using it should result in undefined behaviour. But it seems to be working in my case. Is it simply a case of undefined behaviour can also mean it will work sometimes, or am I overlooking something?

// complex.cc
    Complex& operator/(Complex lhs, const Complex& rhs)
    {
        return lhs /= rhs;
    }
// inside main
    complex::Complex a{3, -6};
    complex::Complex b{1, -5};
    complex::Complex res{a / b};
    std::cout << a << '\n' << b << '\n' << res << std::endl;

As I understand it, shouldn't there be a copy of a created, when I pass it to the overloaded operator, which then returns a reference to the modified copy? Is that understanding wrong, or why does it work when I print it?

答案1

得分: 4

"但在我的情况下似乎正在工作。这只是一种未定义行为的情况,也可能意味着它有时会工作,还是我忽视了某些东西?"

"你没有。行为是未定义的,这意味着它可能看起来像是在工作。"

"正如我理解的那样,当我将它传递给重载运算符时,应该有一个已创建的副本,然后返回对修改后的副本的引用,对吗?"

"这也是正确的 - 并且当函数返回时,副本超出了范围,因此返回的引用是悬挂引用。"

英文:

> But it seems to be working in my case. Is it simply a case of undefined behaviour can also mean it will work sometimes, or am I overlooking something?

You are not. The behavior is undefined, which means that it may look like it's working.

> As I understand it, shouldn't there be a copy of a created, when I pass it to the overloaded operator, which then returns a reference to the modified copy?

That's also correct - and the copy goes out of scope when the function returns so the returned reference is a dangling reference.

huangapple
  • 本文由 发表于 2023年7月3日 04:30:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76600671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定