C++類中的特殊成員函數(shù)示例詳解
前言
C++類中有幾個特殊的非靜態(tài)成員函數(shù),當(dāng)用戶未定義這些函數(shù)時,編譯器將給出默認實現(xiàn)。C++11前有四個特殊函數(shù),C++11引入移動語義特性,增加了兩個參數(shù)為右值的特殊函數(shù)。這六個函數(shù)分別是:
1、默認構(gòu)造函數(shù)
默認構(gòu)造函數(shù)指不需要參數(shù)就能初始化的構(gòu)造函數(shù)。包含無參和所有參數(shù)有默認值兩種類型的構(gòu)造函數(shù)。
2、復(fù)制構(gòu)造函數(shù)
復(fù)制構(gòu)造函數(shù)指使用該類的對象作為參數(shù)的構(gòu)造函數(shù)??梢杂衅渌麉?shù),但必須提供默認值。
3、復(fù)制賦值運算符
重載等號=,將該類的對象賦值給已定義對象。
4、析構(gòu)函數(shù)
沒啥可說的。
5、移動構(gòu)造函數(shù)
C++11新增,該類的右值對象為參數(shù)的構(gòu)造函數(shù),其余同復(fù)制構(gòu)造函數(shù)。
6、移動復(fù)制運算符
同復(fù)制賦值運算符,唯一不同是參數(shù)為右值。
看定義容易迷糊,上代碼就會很清晰:
#include <iostream> #include <string> class Foo { public: std::string s; // 默認構(gòu)造函數(shù) Foo() { std::cout << "default constructor" << std::endl; } // 復(fù)制構(gòu)造函數(shù) Foo(const Foo& foo) { std::cout << "copy constructor" << std::endl; s = foo.s; } // 復(fù)制賦值運算符 Foo& operator=(const Foo& foo) { std::cout << "copy assignment operator" << std::endl; s = foo.s; return * this;} // 移動構(gòu)造函數(shù) Foo(Foo&& foo) { std::cout << "move constructor" << std::endl; s = std::move(foo.s); } // 移動賦值運算符 Foo& operator=(Foo&& foo) { std::cout << "move assignment operator" << std::endl; s = std::move(foo.s); return *this;} }; int main() { Foo foo1; Foo foo2(foo1); foo1 = foo2; Foo foo3(std::move(foo1)); foo2 = std::move(foo3); }
用g++或者clang編譯,加上-fno-elide-constructors -std=c++0x選項。執(zhí)行程序輸出如下:
default constructor
copy constructor
copy assignment operator
move constructor
move assignment operator
結(jié)果是我們預(yù)期的。需要注意的是Foo foo3 = foo1的形式會調(diào)用復(fù)制構(gòu)造函數(shù),不會調(diào)用復(fù)制賦值運算符。原因是Foo foo3 = xxx聲明和定義一個新對象,而賦值是作用在已定義對象。移動賦值運算符同理。
C++11新增了=default和=delete函數(shù)修飾符,提示編譯器使用默認或者刪除默認的特殊函數(shù)。需要注意的是這兩個修飾符只能修飾上述特殊函數(shù),用戶可以用其對特殊函數(shù)進行裁剪。一個例子:
struct Test { // 使用默認構(gòu)造函數(shù) Test() = default; // 刪除復(fù)制賦值運算符 Test& operator=(const Test& test) = delete; // 使用默認析構(gòu)函數(shù) ~Test() = default; };
參考
- https://en.cppreference.com/w/cpp/language/member_functions
- https://stackoverflow.com/questions/43349808/extended-lifetime-of-an-object-returned-from-function
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
詳解C++中如何將構(gòu)造函數(shù)或析構(gòu)函數(shù)的訪問權(quán)限定為private
這篇文章主要介紹了詳解C++中如何將構(gòu)造函數(shù)或析構(gòu)函數(shù)的訪問權(quán)限定為private的方法,文中還解釋了構(gòu)造函數(shù)與虛函數(shù)的區(qū)別,需要的朋友可以參考下2016-03-03詳解C++設(shè)計模式編程中對狀態(tài)模式的運用
這篇文章主要介紹了C++設(shè)計模式編程中對狀態(tài)模式的運用,狀態(tài)模式允許一個對象在其內(nèi)部狀態(tài)改變時改變它的行為,對象看起來似乎修改了它的類,需要的朋友可以參考下2016-03-03