Casting return type
Does casting a variable开发者_开发问答 to another type return a temporary copy of that variable? if so then why can't you reference the temporary variable to a function.
void func(int &i) //error converting parameter 1 from int to int&
{
}
int main()
{
double d = 6.8;
func(int(d));
}
Yes casting returns an rvalue (temporary value), but a mutable reference needs an lvalue.
Try this instead:
int main() {
double d = 6.8;
{
int v = d;
func(v);
d = v; // if the change needs to be reflected back to d.
// note that, even if `func` doesn't change `v`,
// `d` will always be truncated to 6.
}
}
If func
is not going to modify i
, the input argument should be a const reference, which can accept an rvalue.
void func(const int& i);
(but for primitives func(int i)
is going to be more efficient.)
The problem is that when you do int(d)
inside the call to func
, it creates a temporary object. You can't bind a reference to temporary. At least, not until C++0x comes and we get rvalue references (some compilers support them already, but the implementations may not be totally solid). You need to have an int
variable defined to store the converted value, then pass that to the function.
精彩评论