淺析c++ 三大函數(shù)
三大函數(shù)的特殊性
c++三大函數(shù)指的是拷貝構(gòu)造、拷貝賦值、析構(gòu)函數(shù)。這3個函數(shù)比較特殊:
- 一般的類都有這3個函數(shù)
- 這3個函數(shù)一般都是public類型的
- 拷貝構(gòu)造是通過已有的對象來創(chuàng)建新的對象,新創(chuàng)建的對象數(shù)據(jù)和已有的對象相同,拷貝賦值是將已有對象的值拷貝到另一個對象中,析構(gòu)函數(shù)用來內(nèi)存釋放和回收,java中虛擬機會自動回收,但在c++中new出來的對象在堆區(qū),需要我們手動釋放
三大函數(shù)詳解
1 拷貝構(gòu)造. 什么時候會用到拷貝構(gòu)造函數(shù),當我們通過一個已有的對象來構(gòu)造另一個對象的時候;當函數(shù)傳參的時候。
#include<iostream>
using namespace std;
class Test{
private:
int val;
public:
Test(int ival):val(ival){
cout << "Test(int val)構(gòu)造函數(shù)" << endl;
}
Test(const Test &test){
val = test.val;
cout << "Test(const Test &test)構(gòu)造函數(shù)" << endl;
}
~Test(){
cout << "ival: " << val;
cout << " 析構(gòu)函數(shù)被調(diào)用了" << endl;
}
};
void f(Test test){ //這里會調(diào)用拷貝構(gòu)造函數(shù)
}
void f2(){ //f2函數(shù)退出時會調(diào)用析構(gòu)函數(shù)
Test test3(2);
Test test4(test3);
}
int main(){
Test test(1);
cout << "-----------------------------" << endl;
f(test);
cout << "----------------------------" << endl;
f2();
cin.get();
return 0;
}

三大函數(shù).jpg
通過上面的實驗可以看到,通過已有對象創(chuàng)建新的對象的時候會調(diào)用拷貝構(gòu)造;函數(shù)實參到形參傳遞的時候也會調(diào)用拷貝構(gòu)造函數(shù)
2 拷貝賦值. 通過操作符=重載來將已有對象的數(shù)據(jù)拷貝給現(xiàn)有對象,函數(shù)實現(xiàn)的時候要注意對要賦值給的對象已有的數(shù)據(jù)清除(含有指針)
Test & operator= (const Test &test){
val = test.val;
return *this;
}
//main 函數(shù)
Test test4(4);
Test test5(5);
cout << "test5 val= " << test5.getVal() << endl;
test5 = test4;
cout << "test5 val= " << test5.getVal() << endl;

拷貝賦值.jpg
3 析構(gòu)函數(shù).分配在棧上的對象離開作用域的時候?qū)ο髸詣诱{(diào)用析構(gòu)函數(shù),實驗結(jié)果見1圖,f2()函數(shù)中的Test自動調(diào)用析構(gòu)函數(shù)