C++의 RAID
RAII(Resource Acquisition Is Initialization)는 리소스의 수명 주기를 제어하는 C++ 기술입니다. 클래스 변형이며 개체 수명과 관련이 있습니다.
여러 리소스를 클래스로 캡슐화하여 개체 생성 시 생성자에서 리소스 할당을 수행하고 개체 파괴 시 소멸자에서 리소스 할당 해제를 수행합니다.
리소스는 개체가 살아 있을 때까지 유지됩니다.
예시
void file_write {
Static mutex m; //mutex to protect file access
lock_guard<mutex> lock(m); //lock mutex before accessing file
ofstream file("a.txt");
if (!file.is_open()) //if file is not open
throw runtime_error("unable to open file");
// write text to file
file << text << stdendl;
} C++ 및 마이너스의 스마트 포인터
스마트 포인터는 파일 처리, 네트워크 소켓 등과 같은 메모리 관리로 사용할 수 있는 방식으로 일반 포인터를 만들 수 있는 추상 데이터 유형입니다. 또한 자동 소멸, 참조 카운팅 등과 같은 많은 작업을 수행할 수 있습니다.
C++의 스마트 포인터는 * 및 -> 연산자로 오버로드된 템플릿 클래스로 구현할 수 있습니다. auto_ptr, shared_ptr, unique_ptr 및 weak_ptr은 C++ 라이브러리에서 구현할 수 있는 스마트 포인터의 형태입니다.
예시
#include <iostream>
using namespace std;
// A generic smart pointer class
template <class T>
class Smartpointer {
T *p; // Actual pointer
public:
// Constructor
Smartpointer(T *ptr = NULL) {
p = ptr;
}
// Destructor
~Smartpointer() {
delete(p);
}
// Overloading de-referencing operator
T & operator * () {
return *p;
}
// Over loading arrow operator so that members of T can be accessed
// like a pointer
T * operator -> () {
return p;
}
};
int main() {
Smartpointer<int> p(new int());
*p = 26;
cout << "Value is: "<<*p;
return 0;
} 출력
Value is: 26