Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2570186
  • 博文数量: 315
  • 博客积分: 3901
  • 博客等级: 少校
  • 技术积分: 3640
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-08 15:32
个人简介

知乎:https://www.zhihu.com/people/monkey.d.luffy Android高级开发交流群2: 752871516

文章分类

全部博文(315)

文章存档

2019年(2)

2018年(1)

2016年(7)

2015年(32)

2014年(39)

2013年(109)

2012年(81)

2011年(44)

分类: C/C++

2013-05-11 16:38:28


点击(此处)折叠或打开

  1. #ifndef _SHARED_PTR_
  2. #define _SHARED_PTR_

  3. #include <iostream>          // std::cout std::fixed
  4. #include <string>            // std::string
  5. #include <memory>            // std::shared_ptr

  6. using namespace std;

  7. class ZOOM
  8. {
  9. public:
  10.     ZOOM(string name, int id);
  11.     ~ZOOM();
  12. public:
  13.     void showInfo();
  14. public:
  15.     string sName;
  16.     int nId;
  17. };

  18. #endif







  19. // shared_ptr.cpp : 定义控制台应用程序的入口点。
    //


    #include "stdafx.h"
    #include "shared_ptr.h"


    ZOOM::ZOOM(string name, int id)
    {
    sName = name;
    nId = id;
    }


    ZOOM::~ZOOM()
    {


    }


    void ZOOM::showInfo()
    {
    cout << "name: " << sName << "id: " << nId << endl;
    }


    void file_closer(FILE * f) 

    if (NULL != f)
    {
    fclose(f); 
    }
    }


    class FileCloser
    {
    public:
    void operator() (FILE * pFile)
    {
    if (NULL != pFile)
    {
    fclose(pFile);
    }
    }
    };


    int _tmain(int argc, _TCHAR* argv[])
    {
    shared_ptr shpt(new ZOOM("xiaohai", 40805));
    cout << "当前引用计数: " << shpt.use_count() << endl;
    shpt->showInfo();


    shared_ptr blank;
    blank = shpt;
    cout << "当前引用计数: " << shpt.use_count() << endl;
    blank->showInfo();


    {
    shared_ptr blankCur = blank;
    cout << "当前引用计数: " << shpt.use_count() << endl;
    blankCur->showInfo();
    }
    cout << "当前引用计数: " << shpt.use_count() << endl;


    FILE * fp = NULL;
    if (0 == fopen_s(&fp, "log.txt", "w"))
    {
    shared_ptr spLog(fp, file_closer);       ///< 方式一
    shared_ptr spLogF(fp, FileCloser());     ///< 方式二
    cout << spLog.get() << endl;
    cout << spLogF.get() << endl;
    }


    getchar();
    return 0;
    }




阅读(742) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~