我遇到了 gcc 编译器将局部变量(不是临时的)作为右值参数移动到函数的问题。我有一个简单的例子:
class A
{
public:
A() {}
A& operator=(const A&) { std::cout << "const A&\n"; return *this; }
A& operator=(A&&) { std::cout << "A&&\n"; return *this; }
};
class B
{
public:
B() {}
B& operator=(const B&) { std::cout << "const B&\n"; return *this; }
B& operator=(B&&) { std::cout << "B&&\n"; return *this; }
template<class T> B& operator=(const T&) { std::cout << "const T& (T is " << typeid(T).name() << ")\n"; return *this; }
template<class T> B& operator=(T&&) { std::cout << "T&& (T is " << typeid(T).name() << ")\n"; return *this; }
};
int main(int argc, char **argv)
{
A a1;
A a2;
a1 = a2;
B b1;
B b2;
std::cout << "B is " << typeid(B).name() << "\n";
b1 = b2;
}
输出:
const A&
B is 1B
T&& (T is 1B)
我没想到它,因为移动赋值将右值归零。在我的情况下,它导致崩溃,因为在 b1=b2; 之后使用了 b2;
问题是为什么会发生。