C 沉思錄 控制代碼 智慧型指標改寫

2021-09-08 08:55:00 字數 1320 閱讀 5607

c++ 沉思錄也算是c++中的經典書籍,其中介紹oo思想的我覺得很好,但是全書中貫穿了handle,使用引用計數等,也有點不適合現代c++的設計思想。這裡使用shared_ptr 智慧型指標改寫了「控制代碼」這一章的程式,明顯使**量下降,而且管理方便。下面來看**:

#include #include 

using

namespace

std;

class

point;

point(

int x, int

y): xval(x), yval(y){};

point(

const point &p)

int x() const ;

int y() const ;

point& x(int

xv)

;point& y(int

yv)

;private

:

intxval, yval;

};class handle;

handle(

int x,int y): up(new point(x,y)){};//

按建立point的方式構造handle,handle->upoint->point

handle(const point& p): up(new point(p)){};//

建立point的副本

handle(const handle& h): up(h.up);//

此處複製的是handle,但是底層的point物件並未複製,只是引用計數加1

handle& operator=(const handle&h)

;~handle()

;int x() const;

handle& x(int

xv) ;

int y() const;

handle& y(int

yv) ;

intoutputu()

//輸出引用個數

private

: shared_ptr

up;};

intmain()

執行結果:

c:\windows\system32\cmd.exe /c handle_sharedptr.exe

h1(5:6):2

h2(3:4):1

h3(5:6):2

h4(7:8):2

h5(7:8):2

8 9hit any key to close this window...

可見這裡的結果和「控制代碼」這裡的完全一樣。

C 沉思錄 控制代碼2

1 c 沉思錄 控制代碼1 存在問題 控制代碼為了繫結到point的物件上,必須定義乙個輔助類upoint,如果要求控制代碼繫結到point的子類上,那就存在問題了。2 有沒有更簡單的辦法呢?控制代碼使用point 直接繫結到point物件上 包括子類 為了保持多個控制代碼引用計數的一致性,使用in...

C 沉思錄 控制代碼1

1 在 c 沉思錄 類中,使用了 類,存在問題 a 複製,每次建立乙個副本,這個開銷有可能很大 b 有些物件不能輕易建立副本,比如檔案 2 怎麼解決這個問題?使用引用計數控制代碼,對動態資源封裝,控制代碼包含指標,多個控制代碼可以指向同乙個物件。複製的時候,只是複製控制代碼的指標。3 使用引用計數控...

C 沉思錄 控制代碼類1

看了下 c 沉思錄 第六章的內容介紹的是控制代碼第一部分,採用引用計數器的方式減少記憶體的拷貝 動手敲了下 加深點印象,加了點注釋 class point point int x,int y xval x yval y int x const int y const point x int xv p...