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 ...
随机推荐
- jquery + json 操作
jquery 读取集合对象多是要与json进行解析操作的,以下自己经过多方资料查找,终于有一套自己的方式组合. 1.首先创建web services或一般处理程序,用于显示获取Datatable对象 ...
- JS的IE和FF兼容性问题汇总
转自:蓝色理想 以下以 IE 代替 Internet Explorer,以 MF 代替 Mozilla FF 一.函数和方法差异 1. getYear()方法 [分析说明]先看一下以下代码: var ...
- ListView 复制到剪切板
private void 导出ToolStripMenuItem_Click(object sender, EventArgs e) { Clipboard.SetText(GetListView(l ...
- QMessageBox 弹出框上的按钮设置为中文
Qt 默认的弹出框上的按钮式英文,虽然也知道是什么意思,但终究不如中文看着顺眼. QMessageBox box(QMessageBox::Warning,"标题","弹 ...
- document.compatMode的CSS1compat
document.compatMode BackCompat:标准兼容模式关闭.浏览器宽度:document.body.clientWidth: CSS1Compat:标准兼容模式开启. 浏览器宽度: ...
- net发布mvc项目
1.复制 Web 文件夹 2.复制 DLL 文件C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies C ...
- MySQL的varchar定义长度到底是字节还是字符
相信这个问题也会困扰不少人,尤其是使用过其它数据库(如Oracle)的人,之前我也没有太在意这个问题,再加上一些书籍和网上的文章讲的不够细致,又没测试过,导致我一直理解错误.下面通过实例来解释,在开始 ...
- phpcms v9 自定义伪静态的分页函数
因为.这个页面还没做好..等做好了..再给大家演示...... 调用方法:$page_attr=pages_open($num[0]['cun'],$get_page,$max_page,'http: ...
- oracle行转列、列转行
一.行转列 需要将如下格式 转换为: 这就是最常见的行转列,主要原理是利用decode函数.聚集函数(sum),结合group by分组实现的 create table test( id varcha ...
- how to get sharepoint lookup value
SPFieldLookup lookUp1 = properties.ListItem.ParentList.Fields.GetField("Leave_x0020_Type") ...