close


RAII 是C++之父 Bjarne Stroustrup提出來的, 是一種關於物件導向的資源管理, 那為什麼要提出這個呢, 是因為C++這語言沒有資源回收機制, 就因為這樣, 所以我們在寫的時候, 會有機率產生Memory leak, 而RAII主要就是為了解決這個問題提出來的.

 

 

Resource Acquisition Is Initialization or RAII, is a C++ programming technique[1][2] which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the lifetime of an object.

RAII guarantees that the resource is available to any function that may access the object (resource availability is a class invariant, eliminating redundant runtime tests). It also guarantees that all resources are released when the lifetime of their controlling object ends, in reverse order of acquisition. Likewise, if resource acquisition fails (the constructor exits with an exception), all resources acquired by every fully-constructed member and base subobject are released in reverse order of initialization. This leverages the core language features (object lifetime, scope exit, order of initialization and stack unwinding) to eliminate resource leaks and guarantee exception safety. Another name for this technique is Scope-Bound Resource Management (SBRM), after the basic use case where the lifetime of an RAII object ends due to scope exit.

 

 



std::mutex m;
void bad()
{
	m.lock();						// acquire the mutex
	f();							// if f() throws an exception, the mutex is never released
	if (!everything_ok()) return;	// early return, the mutex is never released
	m.unlock();						 // if bad() reaches this statement, the mutex is released
}

void good()
{
	std::lock_guard lk(m); // RAII class: mutex acquisition is initialization
	f();                               // if f() throws an exception, the mutex is released
	if (!everything_ok()) return;       // early return, the mutex is released
}



class file
{
public:
	file(string const& name) {
		m_fileHandle = fopen(name.cstr());
	}
	~file() {
		fclose(m_fileHandle);
	}
	//
private:
	handle m_fileHandle;
}
void fun1() {
	file myfile("my.txt");
	// do something ....
} //destructor



 

 

image

 



#include 
#include 
#include 



using namespace std;

template 
struct AutoLock {
	AutoLock(TLock& lock) :_lock(lock) {
		printf("Lock\n");
		lock.lock();
	}
	~AutoLock() 
	{
		_lock.unlock();
		printf("Unlock\n");
	}
private:
	TLock& _lock;
};
mutex MyMutex;

void DoWork() {
	AutoLocklocker(MyMutex);
	for (int i = 0; i < 3; i++)
	{
		printf("%d \n", i);
	}
	printf("End\n");
}

 



int main()
{
	DoWork();
	DoWork();
	DoWork();
}

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Eric 的頭像
    Eric

    一個小小工程師的心情抒發天地

    Eric 發表在 痞客邦 留言(0) 人氣()