0
#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;
}
以下程序的輸出是編譯:複製省略似乎會發生,即使有-fno-的Elid-構造
Constructor
function
Destructor
爲什麼移動構造函數不是在這裏叫什麼名字?好像就算我編譯旗-fno-的Elid-構造發生複製省略:g++ test.cpp -fno-elide-constructors -std=c++11
我是不是很壯觀?當然'A()'調用默認構造函數,那麼匿名臨時變量可以綁定到'f(A &&)'。我錯過了什麼?移動構造函數只能在構造對象時調用。 – Bathsheba
@Bathsheba:我不認爲你錯過了任何東西。給定'foo();',那麼'A a {foo()};'會調用移動構造函數,但事實上,沒有什麼可移動的。 –
@Bathsheba「我錯過了什麼?」我不知道...一些高質量的個人時間?也許有些睡覺呢? (不要介意我,只是小丑,友好的開玩笑,沒有惡意)。 –