前言
C++類中有幾個(gè)特殊的非靜態(tài)成員函數(shù),當(dāng)用戶未定義這些函數(shù)時(shí),編譯器將給出默認(rèn)實(shí)現(xiàn)。C++11前有四個(gè)特殊函數(shù),C++11引入移動(dòng)語義特性,增加了兩個(gè)參數(shù)為右值的特殊函數(shù)。這六個(gè)函數(shù)分別是:
1、默認(rèn)構(gòu)造函數(shù)
默認(rèn)構(gòu)造函數(shù)指不需要參數(shù)就能初始化的構(gòu)造函數(shù)。包含無參和所有參數(shù)有默認(rèn)值兩種類型的構(gòu)造函數(shù)。
2、復(fù)制構(gòu)造函數(shù)
復(fù)制構(gòu)造函數(shù)指使用該類的對(duì)象作為參數(shù)的構(gòu)造函數(shù)。可以有其他參數(shù),但必須提供默認(rèn)值。
3、復(fù)制賦值運(yùn)算符
重載等號(hào)=,將該類的對(duì)象賦值給已定義對(duì)象。
4、析構(gòu)函數(shù)
沒啥可說的。
5、移動(dòng)構(gòu)造函數(shù)
C++11新增,該類的右值對(duì)象為參數(shù)的構(gòu)造函數(shù),其余同復(fù)制構(gòu)造函數(shù)。
6、移動(dòng)復(fù)制運(yùn)算符
同復(fù)制賦值運(yùn)算符,唯一不同是參數(shù)為右值。
看定義容易迷糊,上代碼就會(huì)很清晰:
#include <iostream>#include <string>class Foo {public: std::string s; // 默認(rèn)構(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ù)制賦值運(yùn)算符 Foo& operator=(const Foo& foo) { std::cout << "copy assignment operator" << std::endl; s = foo.s; return * this;} // 移動(dòng)構(gòu)造函數(shù) Foo(Foo&& foo) { std::cout << "move constructor" << std::endl; s = std::move(foo.s); } // 移動(dòng)賦值運(yùn)算符 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選項(xiàng)。執(zhí)行程序輸出如下:
default constructor
copy constructor
copy assignment operator
move constructor
move assignment operator
結(jié)果是我們預(yù)期的。需要注意的是Foo foo3 = foo1的形式會(huì)調(diào)用復(fù)制構(gòu)造函數(shù),不會(huì)調(diào)用復(fù)制賦值運(yùn)算符。原因是Foo foo3 = xxx聲明和定義一個(gè)新對(duì)象,而賦值是作用在已定義對(duì)象。移動(dòng)賦值運(yùn)算符同理。
C++11新增了=default和=delete函數(shù)修飾符,提示編譯器使用默認(rèn)或者刪除默認(rèn)的特殊函數(shù)。需要注意的是這兩個(gè)修飾符只能修飾上述特殊函數(shù),用戶可以用其對(duì)特殊函數(shù)進(jìn)行裁剪。一個(gè)例子:
struct Test { // 使用默認(rèn)構(gòu)造函數(shù) Test() = default; // 刪除復(fù)制賦值運(yùn)算符 Test& operator=(const Test& test) = delete; // 使用默認(rèn)析構(gòu)函數(shù) ~Test() = default;};參考
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答