RAII(Resource Acquisition Is Initialization)


Resource acquisition is initialization (RAII) is a programming idiom used in several object-oriented languages to describe a particular language behavior.

RAII (Resource Acquisition Is Initialization) is one of the famous design patterns.
The technique was developed for exception-safe resource management in C++ during 198489, primarily by Bjarne Stroustrup and Andrew Koenig.

RAII patterns are important techniques for preventing leakage in languages such as C++ that require developers to directly manage resources.


The following C++11 example demonstrates usage of RAII for file access and mutex locking:

#include <fstream>
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <string>
void WriteToFile(const std::string& message) {
  // |mutex| is to protect access to |file| (which is shared across threads).
  static std::mutex mutex;
// Lock |mutex| before accessing |file|.
  std::lock_guard<std::mutex> lock(mutex);
// Try to open file.
  std::ofstream file("example.txt");
  if (!file.is_open()) {
    throw std::runtime_error("unable to open file");
  }
// Write |message| to |file|.
  file << message << std::endl;
// |file| will be closed first when leaving scope (regardless of exception)
  // mutex will be unlocked second (from lock destructor) when leaving scope
  // (regardless of exception).
}



<Ref : https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization>

#RAII #Resource Acquisition Is Initialization #C++ #mutex #Memory leakage #std::auto_ptr

No comments:

Post a Comment

알뜰폰 삼성페이 교통카드 '한도 초과' 오류(등록 불가 오류) 해결방법

sk7mobile 알뜰폰 삼성페이 교통카드 등록 시, 한도 초과 문제 해결방법 skt usim 해킹 사건으로 인해 sk7mobile 알뜰폰을 사용하는 저도 usim을 바꾸고 나니 삼성페이 교통카드가 등록이 안되더라구요...  삼성페이 교통카드 기능 은...