我现在正在学习 C++ 移动语义,但我对代码打击遇到了麻烦:
#include <iostream>
class A {
public:
A() { std::cout << "Default Constructor\n"; }
A(const A& other) { std::cout << "Copy Constructor\n"; }
A(A&& other) noexcept { std::cout << "Move Constructor\n"; }
// 仅仅是为了避免编译器优化而定义
A& operator=(const A& other) {
std::cout << "Copy Assignment Operator\n";
return *this;
}
A& operator=(A&& other) noexcept {
std::cout << "Move Assignment Operator\n";
return *this;
}
};
void func(A&& a) {
// Do something with 'a'
}
int main() {
A a; // 调用默认构造函数
func(std::move(a)); // 调用移动构造函数
func(A()); // 直接传递右值,调用移动构造函数
return 0;
}
但是输出是
Default Constructor
Default Constructor
void func(A&& a) { }
int main() {
A a; // default constructor
func(std::move(a)); // you are merely creating a reference that allows moving.
// Your func doesn't do anything with it, so no object is created/moved.
func(A()); // again, you create an object (default constructor), then pass it
// to func() as a reference that would allow moving.
return 0;
}