#include <iostream>
class A {
public:
A() { std::cout << "Constructor" << std::endl; }
A(const A& a) { std::cout << "Copy Constructor" << std::endl; }
A& operator=(const A& a) { std::cout << "Copy = operator" << std::endl; }
A(A&& a) { std::cout << "Move Constructor" << std::endl; }
A& operator=(A&& a) { std::cout << "Move = operator" << std::endl; }
~A() { std::cout << "Destructor" << std::endl; }
};
void f(A&& a) { std::cout << "function" << std::endl; }
int main() {
f(A());
return 0;
}
以下程序的输出是:
Constructor
function
Destructor
为什么不在这里调用move-constructor?即使我使用标志-fno-elide-constructors进行编译,似乎也会出现复制省略:g++ test.cpp -fno-elide-constructors -std=c++11
答案 0 :(得分:6)
简短回答:你不是移动构建任何东西。
您只是创建一个临时A
对象,然后传递对它的引用。如果你想看到移动结构,你可以例如将f
的签名更改为
void f(A a)