【发布时间】:2016-11-25 08:45:50
【问题描述】:
#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
为什么这里没有调用移动构造函数?即使我使用标志 -fno-elide-constructors 编译,似乎也会发生复制省略:g++ test.cpp -fno-elide-constructors -std=c++11
【问题讨论】:
-
我是不是特别笨?当然
A()调用默认构造函数,然后匿名临时可以绑定到f(A&&)。我错过了什么?只有当你有一个构造对象时才能调用移动构造函数。 -
@Bathsheba:我认为你没有遗漏任何东西。给定
A foo();,然后A a{foo()};将调用移动构造函数,但事实上,没有什么可移动的。 -
@Bathsheba “我错过了什么?”我不知道... 一些优质的个人时间?也许也有一些睡眠? (别介意我,只是在开玩笑。友好的玩笑,没有恶意)。
-
这不是问题,但不要使用
std::endl,除非你需要它的额外功能;'\n'结束一行。
标签: c++ c++11 move-semantics copy-elision