Skip to content

Instantly share code, notes, and snippets.

@plusangel
Created January 2, 2022 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plusangel/052973b7349907b33d0f82b12978f1a1 to your computer and use it in GitHub Desktop.
Save plusangel/052973b7349907b33d0f82b12978f1a1 to your computer and use it in GitHub Desktop.
RAII example in modern C++ (example b)
cmake_minimum_required(VERSION 3.0.0)
project(raii_examples VERSION 0.1.0)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
add_executable(raii_2 raii_2.cpp)
#include <fstream>
#include <memory>
#include <string_view>
#include <iostream>
void releaseFile(FILE *file)
{
std::cout << "Closing the file" << std::endl;
std::fclose(file);
}
using FileRaii = std::unique_ptr<std::FILE, decltype(&releaseFile)>;
FileRaii acquireFile(std::string_view filename)
{
std::cout << "Opening the file" << std::endl;
FileRaii my_file{std::fopen(filename.data(), "r"), &releaseFile};
if (my_file == NULL)
{
throw std::runtime_error(std::strerror(errno));
}
return my_file;
}
int main()
{
try
{
auto f = acquireFile("sample.txt");
char line[255];
fgets(line, sizeof(line), f.get());
std::cout << line << std::endl;
}
catch (std::runtime_error &e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment