I’m now learning the C++ moving semantics and I have trouble about the code blow:
#include <iostream>
class A {
public:
A() { std::cout << "Default Constructorn"; }
A(const A& other) { std::cout << "Copy Constructorn"; }
A(A&& other) noexcept { std::cout << "Move Constructorn"; }
// 仅仅是为了避免编译器优化而定义
A& operator=(const A& other) {
std::cout << "Copy Assignment Operatorn";
return *this;
}
A& operator=(A&& other) noexcept {
std::cout << "Move Assignment Operatorn";
return *this;
}
};
void func(A&& a) {
// Do something with 'a'
}
int main() {
A a; // 调用默认构造函数
func(std::move(a)); // 调用移动构造函数
func(A()); // 直接传递右值,调用移动构造函数
return 0;
}
But the output is
Default Constructor
Default Constructor
I want to know why the move constructor not be called? And only two default constructor are called? The compiler is “g++ 13.2”