1. 程式人生 > >智慧指標的一種實現

智慧指標的一種實現

std的auto_ptr實現了介面

T* get() 返回原始指標

void reset() 析構原始指標指向的物件

T* operator ->() 返回原始指標

T& operator *() 返回原始指標指向的物件的引用

T* release() 交還原始指標管理權

基於以上功能要求,實現智慧指標如下

#pragma once

template<class T>
class smart_ptr{
public:
	//smart_ptr():m_p(0){}
	smart_ptr(T *p):m_p(p){}
	~smart_ptr();
	T* get() {return m_p;}
	void reset();
	T* release();
	T* operator -> () {return m_p;}
	T& operator *() {return *m_p;}
private:

	smart_ptr(smart_ptr &);   // declare copy constructor and operator = as private to avoid misuse smart_ptr
	smart_ptr& operator =(smart_ptr&);//
	T *m_p;
};

template<class T>
T* smart_ptr<T>::release()
{
	T* temp = m_p;
	m_p = 0;
	return temp;
}

template<class T>
void smart_ptr<T>::reset()
{
	if (m_p)
	{
		delete m_p;
		m_p = 0;
	}
}

template<class T>
smart_ptr<T>::~smart_ptr()
{
	reset();
}


測試類

class testClass
{
public:
	testClass(){cout<<"construction testClass"<<endl;}
	~testClass(){cout<<"destruction testClass"<<endl;}
	void print(){cout<<m_str<<endl;}
	string m_str;
};

測試程式碼

#include <stdio.h>
#include <tchar.h>
#include <string>
#include <ctime>
#include <map>
#include <iostream>
#include <algorithm>
#include "header.hpp"
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	smart_ptr<testClass> sp1(new testClass);
	
	sp1.get()->m_str = "111";
	sp1->print();
	(*sp1).m_str = "2222";
	sp1->print();

	//smart_ptr<testClass> sp2 = sp1;//compile error since copy constructor is declared as private

	testClass *p = sp1.release();
	delete p;
	return 0;
}


相關推薦

智慧指標實現

std的auto_ptr實現了介面 T* get() 返回原始指標 void reset() 析構原始指標指向的物件 T* operator ->() 返回原始指標 T& operator *() 返回原始指標指向的物件的引用 T* release() 交還原

C++ 幾智慧指標的簡單實現

#pragma once// 智慧指標 // 定義個類來封裝資源的分配和釋放,在構造 函式完成資源的分配和初始化,在解構函式完成資源的// 清理,可以 保證資源的正確初始化和釋放。// 這裡簡單實現 AutoPtr、 ScopedPtr、ScopedArray以及 Share

C++實現智慧指標()

參考自《C5-C++ Primer》和實驗樓相關實驗。一. 智慧指標概念智慧指標的引入:C++中,通過new/delete這對運算子進行動態記憶體的管理。動態記憶體使用很容易出問題,因為確保在正確時間釋放記憶體是很困難的。有時忘記釋放記憶體,產生記憶體洩漏;有時在指標還引用記

C++差分隱私的指數機制的實現方法

list and span 機制 namespace stdio.h int class ++ #include <iostream> #include<stdio.h> #include<stdlib.h> #include<m

nginx 301重定向實現方法

pan listen lis return uri www com 瀏覽器 request 1 假設要使用的域名是b.com,以前的老域名是a.com,則以下設置讓nginx把a.com的請求訪問轉發到b.com,並返回301給瀏覽器。 2 server 3

Python3中socket的實現方式

div reply auth email str 兩個 env ini 字符串 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017-06-09 22:57 # @Author : wlgo210

樂觀鎖的實現方式——CAS

www. 提升 中一 num 對象 用戶 ace 另一個 nbsp 原文出處: hollischuang (@Hollis_Chuang) 在深入理解樂觀鎖與悲觀鎖一文中我們介紹過鎖。本文在這篇文章的基礎上,深入分析一下樂觀鎖的實現機制,介紹什麽是CAS、CAS的應用以及C

最大子矩陣的實現方法

targe 空間 pos 右下角 ont 算法 algo 最大子矩陣 AC 題目: 農夫約翰想要在他的正方形農場上建造一座正方形大牛棚。他討厭在他的農場中砍樹,想找一個能夠讓他在空曠無樹的地方修建牛棚的地方。我們假定,他的農場劃分成 N x N 的方格。輸入數據中包括

Java模版方法的另實現

pan strategy 全部 相關 必須 rod () 抽象方法 rate   面試荔枝FM杯具,遂死磕AQS途中發現一個有趣的模版用法,記下來。   模版方法是很重要的設計模式,在數據訪問層、眾多的插件接口都可見其影子,一般的實現都是在模版中定義抽象方法並使用其方法進行

Java並發問題--樂觀鎖與悲觀鎖以及樂觀鎖的實現方式-CAS

RF -- 指針 locking water 更多 錯誤 創建 判斷 首先介紹一些樂觀鎖與悲觀鎖: 悲觀鎖:總是假設最壞的情況,每次去拿數據的時候都認為別人會修改,所以每次在拿數據的時候都會上鎖,這樣別人想拿這個數據就會阻塞直到它拿到鎖。傳統的關系型數據庫裏邊就用到了很多這

比例諧振控制的實現

ID 這樣的 perf fig 適應性 ont tro 特定 結構 原文地址:https://donghao2nanjing.github.io/2018/06/22/PR_Controller/ 1. 比例諧振控制器簡介 首先,我們來看看比例諧振控制器的傳遞函數和伯德圖:

動態內表的實現方式

loop days assign pla eat -name alc str ack SPAN { font-family: "Courier New"; font-size: 10pt; color: #000000; background: #FFFFFF } .L0S

紅包算法的實現(PHP)

rand ray () count ++ 沒有 turn 實現 art 前段時間有個項目需要用到紅包算法,本以為簡單,細想之下有點復雜。於是就百度了一下,沒想到查出了不少,有些寫的很復雜。由於時間有點緊,我就找了一個簡單點的。然後參考著寫一個。參考的地址是:

安卓換膚的實現思路

/* 用於button的切換事件 */ /** * 夜間模式切換 */ private void isNightMode(){ Boolean isNight = sp.getBoolean("night", false);

C++從零開始區塊鏈:main函式的實現

前面已經把各種業務邏輯都寫好了,main函式怎麼呼叫就隨便了,這裡只是其中一種實現方法 int main(int argc, char **argv) { if (argc < 2) { std::cout << "argc error!

byte陣列轉成16進位制字串的實現方式

public String bytes2HexStr(byte[] byteArr) { String hexString = "0123456789ABCDEF"; StringBuilder sb = new StringBuilder(byteArr.lengt

c# 數字ID與可見字串碼互轉的實現

c# 數字ID與可見字串碼互轉的一種實現 適用場景:有時使用者id等之類的欄位用的是int型別,但在有些時候不想讓這個id暴露,於是可以考慮把這個id轉換成一個字串,而且要可根據這個字串得到相應的id值 實現如下程式碼: using System; using System.Data; usi

java 多執行緒的實現方式

private ThreadPoolExecutor threadPoolExecutor; /** * 獲取執行緒池 * @return */ private ThreadPoolExecutor getThreadPoolExecutor(){

邏輯迴歸演算法的實現

"""邏輯迴歸演算法的一種實現__1""" import numpy as np import matplotlib.pyplot as plt """載入資料集,將資料集中兩列資料分別儲存到datamat和labelmat""" def loadDataSet():

吸頂效果的另實現

  前面介紹過一篇文章,是使用ItemDecoration來實現吸頂效果,使用起來很解耦,簡單,方便,但是優缺點是拓展性比較差,今天就通過另一種方式來實現吸頂效果,並且吸頂欄可以高度制定佈局和互動,步入正題,下面來實現它,先看看效果圖: 一、實現原理 頭部的內容位於R