C++類中的特殊成員函數(shù)示例詳解
前言
C++類中有幾個特殊的非靜態(tài)成員函數(shù),當(dāng)用戶未定義這些函數(shù)時,編譯器將給出默認(rèn)實(shí)現(xiàn)。C++11前有四個特殊函數(shù),C++11引入移動語義特性,增加了兩個參數(shù)為右值的特殊函數(shù)。這六個函數(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ù)指使用該類的對象作為參數(shù)的構(gòu)造函數(shù)??梢杂衅渌麉?shù),但必須提供默認(rèn)值。
3、復(fù)制賦值運(yùn)算符
重載等號=,將該類的對象賦值給已定義對象。
4、析構(gòu)函數(shù)
沒啥可說的。
5、移動構(gòu)造函數(shù)
C++11新增,該類的右值對象為參數(shù)的構(gòu)造函數(shù),其余同復(fù)制構(gòu)造函數(shù)。
6、移動復(fù)制運(yùn)算符
同復(fù)制賦值運(yùn)算符,唯一不同是參數(shù)為右值。
看定義容易迷糊,上代碼就會很清晰:
#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;}
// 移動構(gòu)造函數(shù)
Foo(Foo&& foo) { std::cout << "move constructor" << std::endl; s = std::move(foo.s); }
// 移動賦值運(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的形式會調(diào)用復(fù)制構(gòu)造函數(shù),不會調(diào)用復(fù)制賦值運(yùn)算符。原因是Foo foo3 = xxx聲明和定義一個新對象,而賦值是作用在已定義對象。移動賦值運(yùn)算符同理。
C++11新增了=default和=delete函數(shù)修飾符,提示編譯器使用默認(rèn)或者刪除默認(rèn)的特殊函數(shù)。需要注意的是這兩個修飾符只能修飾上述特殊函數(shù),用戶可以用其對特殊函數(shù)進(jìn)行裁剪。一個例子:
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;
};
參考
- 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++實(shí)現(xiàn)進(jìn)程間通信(IPC)的終極指南
進(jìn)程間通信(IPC,Inter-Process Communication),指至少兩個進(jìn)程或線程間傳送數(shù)據(jù)或信號的一些技術(shù)或方法,下面小編來和大家深入介紹一下C++實(shí)現(xiàn)進(jìn)程間通信(IPC)的相關(guān)方法吧2025-04-04
詳解C語言中g(shù)etgid()函數(shù)和getegid()函數(shù)的區(qū)別
這篇文章主要介紹了詳解C語言中g(shù)etgid()函數(shù)和getegid()函數(shù)的區(qū)別,注意getegid只返回有效的組識別碼,需要的朋友可以參考下2015-08-08
c語言中main函數(shù)用法及知識點(diǎn)總結(jié)
在本篇文章里小編給大家分享的是一篇關(guān)于c語言中main函數(shù)用法及知識點(diǎn)總結(jié)內(nèi)容,有需要的朋友們可以跟著學(xué)習(xí)參考下。2021-10-10

