移動建構式
移動建構式就是從拷貝建構式演化而來的,
拷貝建構式又分為淺拷貝和深拷貝:
- 淺拷貝:當類中有指標時,淺拷貝會發生錯誤
- 深拷貝:每次都是重新賦值一份,在某些情況下這種方法可能記憶體消耗較大
因此就產生了移動建構式,
- 將原來物件的東西移動到新的物件上
- 移動后當物件銷毀時不能發生錯誤
- 移動后原物件不再指向被移動的資源,這些資源的所有權已經歸屬新創建的物件
A(A&x){
this->num = new int(*x.num);
cout << "拷貝建構式" << endl;
}
A(A&&x){
this->num = x.num;
x.num = nullptr;
cout << "移動建構式" << endl;
}
上面兩種就是拷貝建構式和移動建構式的對比,
拷貝建構式時,因為類中的資料是指標型別所以在賦值的時候需要重新在堆上創建一個空間,在賦值,而不能直接進行賦值
而移動建構式的目的就是將原物件的東西移動到新物件上面,所以直接賦值就行,但是需要將原物件的指向變為空,

代碼如下:
#include<iostream>
using namespace std;
class A{
public:
A(){
this->num = new int(10);
cout << "建構式" << endl;
}
A(A&x){
this->num = new int(*x.num);
cout << "拷貝建構式" << endl;
}
A(A&&x){
this->num = x.num;
x.num = nullptr;
cout << "移動建構式" << endl;
}
~A(){
cout << "解構式" << endl;
}
int *num;
};
void test(){
A a;
A b=a;
A c(move(a));
}
int main()
{
test();
system("pause");
return 0;
}
運行結果:

移動賦值
從這個引出了移動賦值函式:這個和上面的類似
也是將原物件的東西賦值給新物件,然后原物件指向空
void operator = (A && x){
this->num = x.num;
x.num = nullptr;
cout << "移動賦值函式" << endl;
}
void operator = (A & x){
this->num = new int(*x.num);
cout << "operator=" << endl;
}
跟上面的方法類似,呼叫方法:
A b;
b = a; //使用operator=
A c;
c = move(a); //使用移動賦值函式
代碼:
#include<iostream>
using namespace std;
class A{
public:
A(){
this->num = new int(10);
cout << "建構式" << endl;
}
void operator = (A && x){
this->num = x.num;
x.num = nullptr;
cout << "移動賦值函式" << endl;
}
void operator = (A & x){
this->num = new int(*x.num);
cout << "operator=" << endl;
}
~A(){
cout << "解構式" << endl;
}
int *num;
};
void test(){
A a;
A b;
b = a;
A c;
c = move(a);
}
int main()
{
test();
system("pause");
return 0;
}
運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/254788.html
標籤:其他
上一篇:Linux系統呼叫原理及實作
