c**********e 发帖数: 2007 | 1 For example, I have a function
Type1& func1(int x)...
How can I call the function func1()? |
c**********e 发帖数: 2007 | 2 I tried something like
Type1& x=func1(5);
It causes Bus error. Does anybody have an idea how to use
func1()? Thanks a lot. |
c**********e 发帖数: 2007 | 3 Could anybody please helpppppppppppppppppppp? |
h*******e 发帖数: 225 | 4 something is wrong with your function
【在 c**********e 的大作中提到】 : I tried something like : Type1& x=func1(5); : It causes Bus error. Does anybody have an idea how to use : func1()? Thanks a lot.
|
c**********e 发帖数: 2007 | 5 Thanks. Which is the right way to call the function?
(a) Type1& x=func1(5);
(b) Type1 x=func1(5);
(c) Type1 x; x=func1(5);
(d) Type1& x; x=func1(5);
【在 h*******e 的大作中提到】 : something is wrong with your function
|
w******p 发帖数: 166 | 6 if ur function is like this:
Type1& func1(int x) {
Type1 ret;
return ret;
}
you are returning reference to local variable, after the call stack of func1
is wrapped up, ret is not guranteed to be valid anymore, hence bus error
may happen.
Just do
Type1 func1(int x) {
Type1 ret;
return ret;
}
modern compiler will prob. optimize off the copy in the return statement by
NRV (Named Return Value) optimization.
If you do need to have the func return by reference, you need to pass in the
referenc |