[英]C++ default move operation in “Effective Modern C++”
第17項:了解特殊成員函數生成。
移動操作僅針對缺少類別生成
顯式聲明了移動操作,復制操作或析構函數。
現在,當我提到移動操作移動構建時
或移動 - 分配數據成員或基類
並不保證會實際采取行動。
實際上,“成員行動”更像是成員
移動請求,因為未啟用移動的類型(...)
將通過他們的復制操作“移動”。
但是,我無法在我的環境中驗證它們。
// compiled
#include <iostream>
using namespace std;
class Base {
public:
~Base() {}
};
int main() {
Base a, c;
Base b(move(a));
c = move(b);
// explicitly destructor does not disable
// default move constuctor and move assignment operator
return 0;
}
class Base {
public:
Base() {}
Base(Base& b) {}
~Base() {}
};
class Num {
private:
Base b;
};
int main() {
Num a, c;
c = move(a); // passed
Num b(move(c)); // error
// explicitly Base::Base(Base& b) disable default move
// move conctructor.
// Num's default move constructor can not find any move
// constructor for member object Base b, which lead to an
// error. Num's default move constructor does not "moved"
// Base b via their copy operations which is declared.
return 0;
}
第一個斷言可能因不同的環境而異,但第二個斷言幾乎是錯誤的。
我很困惑。 請幫幫我。
class Base {
public:
~Base() {}
};
因為Base
有一個用戶聲明的析構函數,所以根本沒有移動構造函數或移動賦值運算符。 線條
Base b(move(a));
c = move(b);
實際上分別調用復制構造函數和復制賦值運算符。
class Base {
public:
Base() {}
Base(Base& b) {}
~Base() {}
};
class Num {
private:
Base b;
};
同樣, Base
根本沒有移動構造函數。 但是, Num
確實有一個隱式聲明的移動構造函數,因為Num
本身並沒有聲明任何特殊的成員函數。 但是,它被隱式定義為已刪除,因為默認定義將是格式錯誤的:
Num::Num(Num&& n) : b(std::move(n.b)) {}
// Cannot convert rvalue of type `Base` to `Base&`
// for the copy constructor to be called.
請注意, b
的“移動” 確實嘗試使用復制構造函數,但它不能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.