栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++编程小技巧

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++编程小技巧

boost内存池(线程安全)

#include 
typedef  boost::singleton_pool   NewDataPool;

NewData *p = (NewData*)NewDataPool::malloc();   申请内存
NewDataPool::free(p); 释放

noncopyable禁止拷贝操作

#include 
class Astr:private boost::noncopyable
{
public:
	Astr(){};
	virtual ~Astr(){};
};
int main()
{
	Astr A;
	Astr B=A;  //错误禁止拷贝
	Astr *p = &A; //可以
·	return 0;		
}


单例模板

#pragma once
#include 
using namespace std;

template 
class CSingleton
{
public:
	static inline T* Instance();     
private:
	CSingleton(void){} 
	~CSingleton(void){}
};




template 
inline T* CSingleton::Instance()
{
	static auto_ptr Ainstance;
	if( 0 == Ainstance.get() )
	{
		if( 0== Ainstance.get())
		{
			Ainstance.reset ( new T);
		}
	}
	return Ainstance.get();
}

std::set 的使用【自定义结构(两个参数)】

class SortEntrust
{
public:
	bool   operator()(Entrust_ptrconst &pSrc, Entrust_ptrconst &pSec)const
	{
		return strcmp(pSrc->m_cOrderID, pSec->m_cOrderID) >0; //按需求修改
	}
};

std::set     // DayEntrust;委托的数据,SortEntrust是重载()的类

enable_shared_from_this [boost或std都有](shared_ptr 管理的对象的内部获取自己的 shared_ptr)

struct A
{
    void fun()
    {
        shared_ptr sp{this};
        cout<count()<fun(); //输出为1
在 func 函数构造智能指针时, 我们无法确定这个对象是不是被 shared_ptr 管理着, 因此这样构造的 shared_ptr 并不是与其他 shared_ptr 共享一个计数器, 那么, 在析构时就会导致对象被重复释放, 从而引发错误.(调用了两次析构)


struct B: public std::enable_shared_from_this
{
  void fun()
  {
    shared_ptr sp{shared_from_this()};
    cout<count()<fun(); //输出为2

std::bind (boost::bind) 利用bind可以传入多个参数,创建指定类型的函数

typedef boost::function CallBack;
void DoSvc(CallBack  back);  //需要的是三个参数的函数

auto callFunc = [](Struct& req, int Ret, int AskType, std::string& OutStr)mutable
	{
		//内部可修改req的值
	};

//利用bind传入四个参数(或者更多个)构造三个参数类型的函数
CallBack fun = std::bind(callFunc, req, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);

DoSvc(fun );



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/528869.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号