'Reference to lvalue or rvalue for fundamental types or object [duplicate]
I observe a different behavior for the compiler with the 2 following snippets of code:
With the first one, all seems OK to me with fundamental type like int:
void fi1(int& a) {}
void fi2(int&& a) {}
void func1() {
fi1(2+2); // Do not compile: normal since '2+2' is temporary and is not a variable
int a = 5;
fi2(a); // Do not compile: normal since 'a' is an lvalue
}
But I do not understand the second one with object type:
void fs1(string& a) {}
void fs2(string&& a) {}
void func2() {
fs1(string{""}); // Compile: but weird for me since there is no variable to reference !
fs2(string{""}); // Compile: normal since 'string{""}' is temporary and is not a variable
}
In the following post: Understanding lvalue/rvalue expression vs object type
it is explained that an lvalue is when you can take its address. For sure, string{""} shall have an address somewhere in memory. But for me a key-point with rvalue is that you can't use it afterwards, making 'move semantic' possible.
When you are in fs2 function, the argument is an rvalue and you can do whatever you want without any side effect. In fs1, you expect that some variable elsewhere will have some impact if you modify it. fs2 should only be called with variable argument.
And why is working as expected with int and not with object ?
Solution 1:[1]
This strange behavior is due to the usage of MSVC.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jean-Luc Delarbre |
