智能指针的实现----C++练手项目

来源:互联网 发布:随机森林算法 原理图 编辑:程序博客网 时间:2024/05/21 12:42

  1.学习C++过程中,总会去思考,怎么才能去提高自己的编程水平,毕竟,我是个菜鸟,我需要去练习来维持我的学习状态。

正如古人所说的,纸上谈兵。我觉得纸上谈兵也是一种很厉害的东西,但是我是个菜鸟,还没能达到纸上谈兵的阶段。所以

按照知乎上所说的,平常多看代码,每天,保持练习,才能入门C++。

  2.听从前人的经验,刚开始,没有水平能够自己创造就去抄,应该叫做默写,先理解智能指针是什么?有什么用?怎么实现?

然后,自己理解,最后默写。

  3.什么是智能指针?

概括网上的几种版本,大同小异。

(版本1)智能指针是对指针的一种封装,让它成为一个类,来干指针的功能。

(版本2)智能指针是一种pointer-like class,其中必须有一个真正的指针,通过对类的编写来实现一个指针类。

  4.为什么要有智能指针?

因为在使用普通的指针的时候,我们需要去调用delete来释放内存,如果忘记调用delete的话会造成内存泄露,另外一方面,程序

进入异常进入catch块会忘记释放内存。并且,如果我们多次去释放同一个指针会造成程序奔溃,通过智能指针就能够解决。

  5.在标准库中有哪些智能指针?

auto_ptr (C++2.0版本前) 了解它:点击打开链接

shared_ptr (C++2.版本后) 点击打开链接

weak_ptr 点击打开链接

unique_ptr 点击打开链接

  6.智能指针类简单功能重写

(1)构造函数

(2)拷贝构造

(3)拷贝赋值

(4)析构函数

(5)操作符*重载

(6)操作符&冲澡

(7)reference counting

以下是自己默写的smart类:

#pragma once#ifndef _smart#define _smart#include <memory>#include <iostream>#include <assert.h>using namespace std;template<typename T>class smart{private:T* _ptr;size_t* _count; //reference countingpublic://ctorsmart(T* ptr = nullptr):_ptr(ptr){if (_ptr){_count = new size_t(1);}else{_count = new size_t(0);}}//拷贝构造smart(const smart& ptr){if (this != &ptr){this->_ptr = ptr._ptr;this->_count = ptr._count;(*this->_count)++;}}//重载operator=smart operator=(const smart& ptr){if (this->_ptr == ptr._ptr){return *this;}if (this->_ptr){(*this->_count)--;if (this->_count == 0){delete this->_ptr;delete this->_count;}}this->_ptr = ptr._ptr;this->_count = ptr._count;(*this->_count)++;return *this;}//operator*重载T& operator*(){if (this->_ptr){return *(this->_ptr);}}//operator->重载T& operator->(){if (this->_ptr){return this->_ptr;}}//dtor~smart(){(*this->_count)--;if (*this->_count == 0){delete this->_ptr;delete this->_count;}}//return reference countingsize_t use_count(){return *this->_count;}};#endif // !_smart
以下是测试程序:

// smart指针重写.cpp: 定义控制台应用程序的入口点。//#include "stdafx.h"#include "smart.h"#include <iostream>#include <memory>using namespace std;int main(){smart<int> sm(new int(10));cout << "operator*():" << *sm << endl;cout << "reference counting:(sm)" << sm.use_count() << endl;smart<int> sm2(sm);cout <<"copy ctor reference counting:(sm)"<< sm.use_count() << endl;smart<int> sm3;sm3 = sm;cout <<"copy operator= reference counting:(sm)"<< sm.use_count() << endl;cout << &sm << endl;    return 0;}

最后给自己布置一个任务,两天内,去把智能指针的源码再看一遍。

原创粉丝点击