C++ RAII手法实例,不使用智能指针
/*
* =====================================================================================
*
* Filename:
*
* Description: Common function
*
* Version: 1.0
* Created: 2015年11月25日 16时11分13秒
* Revision: none
* Compiler: g++
*
* Author: betachen
* Company:
*
* =====================================================================================
*/ #ifndef __X__H__20151026__
#define __X__H__20151026__ #include <iostream>
#include <string>
#include <cstdarg>
#include <cstdio>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <assert.h> // MutexLock
class MutexLock
{
public:
MutexLock(): holder_(0)
{
pthread_mutex_init(&mutex_, NULL);
}
~MutexLock()
{
assert(holder_ == 0);
pthread_mutex_destroy(&mutex_);
}
bool isLockedBySelf() {return holder_ == pthread_self();}
void lock()
{
pthread_mutex_lock(&mutex_);
holder_ = pthread_self();
}
void unlock()
{
holder_ = 0;
pthread_mutex_unlock(&mutex_);
}
pthread_mutex_t* getPthreadMutex(){return &mutex_;} private:
MutexLock(const MutexLock& rx);
MutexLock& operator=(const MutexLock&); private:
pthread_mutex_t mutex_;
pthread_t holder_;
}; // MutexLockGuard
class MutexLockGuard
{
public:
explicit MutexLockGuard(MutexLock& lock):mutex_lock_(lock)
{
mutex_lock_.lock();
}
~MutexLockGuard()
{
mutex_lock_.unlock();
} private:
MutexLockGuard();
MutexLockGuard(const MutexLockGuard& rx);
MutexLockGuard& operator=(const MutexLockGuard& rx); private:
MutexLock& mutex_lock_;
}; //Condtion for threading
class Condition
{
public:
explicit Condition(MutexLock& mutex):mutex_(mutex)
{
pthread_cond_init(&cond_, NULL);
}
~Condition(){pthread_cond_destroy(&cond_);} void wait()
{
pthread_cond_wait(&cond_, mutex_.getPthreadMutex());
} void notify()
{
pthread_cond_signal(&cond_);
}
void notifyAll()
{
pthread_cond_broadcast(&cond_);
} private:
MutexLock& mutex_;
pthread_cond_t cond_;
}; //CountDownLatch
class CountDownLatch
{
public:
explicit CountDownLatch(int count):count_(count), cond_(mutex_){}
void wait()
{
MutexLockGuard lock(mutex_);
while (count_ > 0)
{
cond_.wait();
}
}
void countDown()
{
MutexLockGuard lock(mutex_);
count_--;
if (count_ == 0)
{
cond_.notifyAll();
}
}
private:
int count_;
mutable MutexLock mutex_;
Condition cond_; }; // FileHandle
class FileHandle
{
public:
FileHandle(const char* s, const char* sMode):file_name_(s)
{
file_ = fopen(s, sMode);
if (file_ == NULL)
{
std::cerr<<s<<" open failed"<<std::endl;
}
}
FileHandle(const std::string& s, const char* sMode):file_name_(s)
{
std::cout<<file_name_<<" opened"<<std::endl;
file_ = fopen(s.c_str(), sMode);
if (file_ == NULL)
{
std::cerr<<s<<" open failed"<<std::endl;
}
}
~FileHandle()
{
if (file_)
fclose(file_);
}
FILE* get(){return file_;}
std::string& get_name(){return file_name_;}; private:
FileHandle();
FileHandle(const FileHandle& rx);
FileHandle& operator = (const FileHandle& rx); protected:
FILE* file_;
std::string file_name_;
}; // has lock for threading
class Loger:public FileHandle
{
public:
Loger(const char* s):FileHandle(s, "a+"){}
Loger(const std::string& s):FileHandle(s, "a+"){}
void _(const char* sFile, const int iLine, const char* sFormat, ...)
{
va_list sList;
va_start(sList, sFormat);
gettimeofday(&tt, NULL);
ttt = localtime(&tt.tv_sec);
//time pid file line
fprintf(file_, "%04d%02d%02d-%02d:%02d:%02d.%03ld|%6d|%15s|% 5d|-> ",
ttt->tm_year+1900,ttt->tm_mon,ttt->tm_mday, ttt->tm_hour, ttt->tm_min, ttt->tm_sec,
tt.tv_usec/1000, getpid() ,sFile, iLine);
vfprintf(file_, sFormat, sList);
fprintf(file_, "\n");
va_end(sList);
}
void _(int lock_flag, const char* sFile, const int iLine, const char* sFormat, ...)
{
MutexLockGuard lock(lock_);
va_list sList;
va_start(sList, sFormat);
gettimeofday(&tt, NULL);
ttt = localtime(&tt.tv_sec);
fprintf(file_, "%04d%02d%02d-%02d:%02d:%02d.%03ld|%6d|%15s|% 5d|-> ",
ttt->tm_year+1900,ttt->tm_mon,ttt->tm_mday, ttt->tm_hour, ttt->tm_min, ttt->tm_sec,
tt.tv_usec/1000, getpid() ,sFile, iLine);
vfprintf(file_, sFormat, sList);
fprintf(file_, "\n");
va_end(sList);
} private:
Loger();
Loger(const Loger& rx);
Loger& operator = (const Loger& rx);
private:
struct tm* ttt;
struct timeval tt;
mutable MutexLock lock_;
}; #define NO_LOCK __FILE__,__LINE__
#define LOCK 1,__FILE__,__LINE__ //Loger log("webtest.log");
//#define _ log._ // To String
#include <algorithm>
template <typename T>
inline std::string toString(const T& value)
{
T i = value;
static const char* sDigits = "0123456789"; char buf[64] = "";
char* p = buf;
do{
int lsd = static_cast<int>(i % 10);
i /= 10;
*p++ = sDigits[lsd];
}while(i != 0); if (value < 0)
{
*p++ = '-';
}
*p = '\0';
std::reverse(buf, p); return buf;
} #endif
C++ RAII手法实例,不使用智能指针的更多相关文章
- enote笔记法使用范例(2)——指针(1)智能指针
要知道什么是智能指针,首先了解什么称为 “资源分配即初始化” what RAII:RAII—Resource Acquisition Is Initialization,即“资源分配即初始化” 在&l ...
- 使用智能指针来管理对象 (基于RAII)
////一个简单的防止内存泄露的例子//void test() { //使用RAII的特性管理资源 //当智能指针unique_ptr被销毁时,它指向的对象也将被销毁 //这里test函数返回后 p将 ...
- 你应该掌握的C++ RAII手法:Scopegaurd
C++作为一门Native Langueages,在C++98/03时代,资源管理是个大问题.而内存管理又是其中最大的问题.申请的堆内存需要手动分配和释放,为了确保内存正确释放,一般原则是" ...
- 「C++」理解智能指针
维基百科上面对于「智能指针」是这样描述的: 智能指针(英语:Smart pointer)是一种抽象的数据类型.在程序设计中,它通常是经由类型模板(class template)来实做,借由模板(tem ...
- [5] 智能指针boost::shared_ptr
[1]boost::shared_ptr简介 boost::shared_ptr属于boost库,定义在namespace boost中,包含头文件#include<boost/shared_p ...
- c++ 智能指针(转)
智能指针的使用 智能指针是在 <memory> 标头文件中的 std 命名空间中定义的. 它们对 RAII 或“获取资源即初始化”编程惯用法至关重要. 此习惯用法的主要目的是确保资源获取与 ...
- RAII手法封装互斥锁
RAII手法是 Resource Acquisition is Initialization 的缩写,意为“资源获取即初始化”,在使用智能指针时也使用,下面是针对互斥量时的实现, #include & ...
- Boost智能指针-基础知识
简单介绍 内存管理一直是 C++ 一个比較繁琐的问题,而智能指针却能够非常好的解决问题,在初始化时就已经预定了删除.排解了后顾之忧.1998年修订的第一版C++标准仅仅提供了一种智能指针:std::a ...
- C++ 中的智能指针-基础
简介 在现代 C++ 编程中,标准库包含了智能指针(Smart pointers). 智能指针用来确保程序不会出现内存和资源的泄漏,并且是"异常安全"(exception-safe ...
随机推荐
- ImageLoader(多线程网络图片加载)+本地缓存 for windowsphone 7
搞了好长一阵子wp,做点好事. C/S手机app中应用最多的是 获取网络图片,缓存到本地,展示图片 本次主要对其中的delay:LowProfileImageLoader进行修改,在获取图片的时候, ...
- Linux 通过 shell 脚本修改密码
交互方式修改密码 1. ssh 远程到主机: 2. 切换到root账号: [一般都是切换到root进行密码修改,如果普通用户修改自己的密码,要输入原密码,然后新密码要满足复杂度才OK]: 3. pas ...
- Linux 下添加普通用户,登陆并删除
adduser 命令.LINUX创建用户的命令useradd -g test -d /home/test1 -s /etc/bash -m test1注解:-g 所属组 -d 家目录 -s 所用的SH ...
- [原创] linux课堂-学习笔记-目录及概况
本学习笔记基于:网易云课堂-linux课堂 课时1Centos 6.4安装讲解46:14 课时2Centos 6.4桌面环境介绍与网络连接04:30 课时3 Linux目录结构介绍及内核与shell分 ...
- winfrom 水晶按钮
闲来无事,从网上找了不少自定义控件,然后整理了一下,做了一个水晶按钮 /// <summary> /// 表示 Windows 的按钮控 /// </summary> [Des ...
- 配置ADB 工具 (Win7_64)
ADB (Android Debut Bridge) ADB这个工具, 让我们可以用电脑来操纵手机 Android studio 安装好之后在SDK 中就有ADB 但是我们想使用它还需要配置它的环境变 ...
- SQL动态更新表字段 传入字段可能为空
小技巧: 项目组有修改产品的基本信息字段 但有时候传入的字段可能为空 也可能不为空 动态修改表中字段. USE [BetaProductMarket_DB] GO )) BEGIN DROP PRO ...
- Unix/Linux中shell调用sqlplus的方式
Unix/Linux下,shell脚本调用sqlplus的几种方式介绍: 一.最简单的shell调用sqlplus #!/bin/bash sqlplus -S /nolog > sqlplus ...
- SRM 616 ColorfulCoins
题意:给定一个从小到大的货币面值,每一个面额都是其前面面额的倍数(倍数大于等于2),每一种货币面值对应一种颜色,目前不清楚面值与颜色的对应关系.要求用最少的查询次数来确定面额与颜色的对应关系.(一次查 ...
- How to open MS word document from the SharePoint 2010 using Microsoft.Office.Interop.dll
or this you must change the identity of word component inC:\windows\System32\comexp.mscto be interac ...