开发者

Codepad.org C++ code gives wrong result

开发者 https://www.devze.com 2023-04-11 04:22 出处:网络
Just a tiny question: Can you tell me what\'s the issue here in this code ? It should print out 9 but it does 4.8921e-270, however, when uncommenting line 4, it works just fine, too.

Just a tiny question:

Can you tell me what's the issue here in this code ? It should print out 9 but it does 4.8921e-270, however, when uncommenting line 4, it works just fine, too.

I don't understand what might be wrong here. Thank you !

Code:

double& foo() {
  double x = 9;
  double &y = x;
  //cout开发者_开发知识库 << y << "\n";
  return y;
}

int main() {
  cout << foo() << "\n";
}

Result: 4.8921e-270


It is a bad idea to return references/pointers to objects on the stack. They are likely destroyed when you leave the function. Try returning it as per value:

double foo() {
  double x = 9;
  double &y = x;
  //cout << y << "\n";
  return y;
}

Now the return value is copied instead of a reference to an object that is probably not existing anymore.


You are returning a reference to a local object, the object ceases to exist when foo completes, and then you get Undefined Behavior when you dereference it.


double foo() {
  double x = 9;
  double &y = x;
  //cout << y << "\n";
  return y;
}

Never a good idea to return references to objects on stack. Most likely they would be disappear when you leave the function. You might try returning it as per value.


You return a reference to a local variable - since the local variable goes out of scope as soon as foo() returns, the value no longer exists.

So you should either just change the return type to double (highly recommended) and return x or (if you absolutely want/have to return a reference) use a static variable instead:

double& foo() {
  static double x = 9;
  double &y = x;
  return y;
}


I often return data members of a class by const ref:

class BigThing {...};

class Foo
{
public:
   const BigThing & getBT() const { return bt; } // For constant BigThing.
   BigThing & getBT() { return bt; } // For mutable BigThing.
private:
   BigThing bt;
};

Then as long as your instance of Foo is in scope (you don't want to return a ref to a local variable) then using one of the getBT() should be safe and efficient.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号