Please tell me why move assignment is called in the following code.
In expression return Foo(static_cast<int>(value));
, static_cast<int>(value)
is rvalue, so move assignment is called. However, in expression return Foo(value);
, value
is an lvalue. Why move assignment is called instead of Foo(int val)
;
#include <bits/stdc++.h>
using namespace std;
class Foo {
public:
Foo() {}
Foo(int val)
{
value = val;
}
Foo(Foo& foo)
{
value = foo.value;
cout << "call Foo(Foo& foo)" << endl;
}
Foo(Foo&& foo)
{
value = foo.value;
foo.value = 0;
cout << "call Foo(Foo &&foo)" << endl;
}
Foo& operator=(Foo &foo)
{
value = foo.value;
cout << "call operator=(Foo& foo)" << endl;
return *this;
}
Foo& operator=(Foo &&foo)
{
value = foo.value;
foo.value = 0;
cout << "call operator=(Foo&& foo)" << endl;
return *this;
}
private:
int value;
};
Foo operator"" fo(unsigned long long value)
{
if (value < INT_MAX) {
// return Foo(static_cast<int>(value)); // call operator=(Foo&& foo)
return Foo(value); // call operator=(Foo&& foo)
} else {
throw "Over Range";
}
}
int main()
{
Foo foo;
foo = 123fo;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire