RAII 资源获取即初始化技术
资源:网络套接字、互斥锁、文件句柄和内存等等,它们属于系统资源,数量有限且对系统正常运行具有一定作用的元素。
如果把资源用类进行封装起来,对资源操作都封装在类的内部,在析构函数中进行释放资源。当定义的局部变量的生命结束时,它的析构函数就会自动的被调用。
引用别人的代码
https://www.jianshu.com/p/b7ffe79498be
#include <iostream>
#include <windows.h>
#include <process.h>
using namespace std;
CRITICAL_SECTION cs;
int gGlobal = 0;
class MyLock
{
public:
MyLock()
{
EnterCriticalSection(&cs);
}
~MyLock()
{
LeaveCriticalSection(&cs);
}
private:
// DISALLOW_COPY_AND_ASSIGN(MyLock);
MyLock( const MyLock &);
MyLock operator =(const MyLock &);
};
void DoComplex(MyLock &lock ) // 非常感谢益可达犀利的review 2014.04.13
{
}
unsigned int __stdcall ThreadFun(PVOID pv)
{
MyLock lock;
int *para = (int *) pv;
// I need the lock to do some complex thing
DoComplex(lock);
for (int i = 0; i < 10; ++i)
{
++gGlobal;
cout<< "Thread " <<*para<<endl;
cout<<gGlobal<<endl;
}
return 0;
}
int main()
{
InitializeCriticalSection(&cs);
int thread1, thread2;
thread1 = 1;
thread2 = 2;
HANDLE handle[2];
handle[0] = ( HANDLE )_beginthreadex(NULL , 0, ThreadFun, ( void *)&thread1, 0, NULL );
handle[1] = ( HANDLE )_beginthreadex(NULL , 0, ThreadFun, ( void *)&thread2, 0, NULL );
WaitForMultipleObjects(2, handle, TRUE , INFINITE );
return 0;
}
在使用CRITICAL_SECTION时,EnterCriticalSection和LeaveCriticalSection必须成对使用,很多时候,经常会忘了调用LeaveCriticalSection,此时就会发生死锁的现象。
对CRITICAL_SECTION的访问封装到MyLock类中时,之后,只需要定义一个MyLock变量,而不必手动的去显示调用LeaveCriticalSection函数。
智能指针
智能指针:C++11引入智能指针,方便管理堆内存,具体表现在:1. 忘记释放指针;2. 二次释放指针。
存在中,auto_ptr、shared_ptr、unique_ptr、weak_ptr
- auto_ptr,适合用来管理生命周期比较短或者不会被远距离传递的动态对象,最好局限在某个函数内部或者某个类的内部,动态对象的产生,使用和销毁的全过程是处于一个小的受控范围。
auto_ptr不能共享所有权,不能指向数组,不能作为容器的成员。 - shared_ptr ,多个指针指向相同的对象,std::make_shared 消除显式地使用 new
#include <iostream>
#include <memory>
void foo(std::shared_ptr<int> i){
(*i)++;
}
int main()
{
// 以std::make_shared 会分配创建传入参数中的对象,并返回这个对象类型的std::shared_ptr指针
auto pointer = std::make_shared<int>(10);
auto pointer2 = pointer; // 引用计数+1
auto pointer3 = pointer; // 引用计数+1
int * p = pointer.get(); // 这样不会增加引用计数,get()获取原始指针
int count = pointer.get_count(); // 引用计数
pointer2.reset(); // 主动释放,引用计数-1
foo(pointer);
std::cout << *pointer << std::endl;
return 0; // 离开作用域之前 shared_ptr会被析构
}
- std::unique_ptr,独占的智能指针,禁止其他智能指针于其共享同一个对象。
std::unique_ptr<int> pointer = std::make_unique<int>(10);
std::unique_ptr<int> pointer2 = pointer; // 非法
// 实现std::make_unique(C++11 没有)
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique(Args&& ...args){
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
虽然不可以复制,但是可以转移
#include <iostream>
#include <memory>
struct Foo{
Foo(){std::cout << "Foo::Foo" << std::endl;}
~Foo(){std::cout << "Foo::~Foo" << std::endl;}
void foo(){std::cout << "Foo::foo" << std::endl;}
}
void f(const Foo&){
std::cout << "f(const Foo&)" << std::endl;
}
int main()
{
std::unique_ptr<Foo> p1(std::make_unique<Foo>());
if(p1)
p1->foo();
{
std::unique_ptr<Foo> p2(std::move(p1));
f(*p2);
if(p2)
p2->foo();
if(p1)
p1->foo();
p1 = std::move(p2);
if(p2)
p2->foo();
std::count << "p2 被销毁" << std::endl;
}
if(p1)
p1->foo();
}
- std::weak_ptr
struct A;
struct B;
struct A{
std::shared_ptr<B> pointer;
~A(){std::cout << "A被销毁" << std::endl;}
};
struct B{
std::shared_ptr<A> pointer;
~B(){std::cout << "B被销毁" << std::endl;}
};
int main(){
auto a = std::make_shared<A>();
auto b = std::make_shared<B>();
a.pointer = b;
b.pointer = a;
}
a,b内部的pointer同时引用了a,b使得a,b的引用计数均等于2,而离开作用域时,智能指针只析构一次,所以a,b指向的内存区域引用计数!=0,而外部又没办法得到这块内存,内存泄露。
std::share_ptr 是一种强引用,std::weak_ptr是一种弱引用