Tuesday Coding Tip 17 — Wrapping C APIs

●5 ●38 ●98
calendar_today • schedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


Resource Acquisition is Initialization (RAII) is an awfully named principle saying that your class should be fully usable after construction and should clean itself up in the destructor (in other words, no (de)init methods). This principle is common in modern programming languages and is also adopted in modern C++ codebases.

But what if you work with C-like API like fopen? It returns a pointer you need to manually free before it goes out of scope. Otherwise, you leak memory and open file handles. This is where smart pointers come to the rescue as you can wrap raw pointers with them and give them custom callbacks to execute when they leave the scope.

#include <cstdlib>
#include <iostream>
#include <memory>

// MSVC disallows calling fopen
#pragma warning(disable : 4996)

void CloseFile(FILE* f)
{
    std::cout << "Closing file" << std::endl;
    fclose(f);
}

auto SafeFopen(const char* path, const char* mode)
{
    return std::unique_ptr<FILE, decltype(&CloseFile)>(
        fopen(path, mode), CloseFile);
}

int main()
{
    auto&& fp = SafeFopen("myfile.txt", "w");
    return 0;
    // Outputs: Closing file
}

Want more #programming & #programming deep dives?

Join 6,134+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

Part 17 of 33 in Tuesday Coding Tips

1 Comment

0 votes

More Posts

Tuesday Coding Tip 33 — Imported CMake targets

Jakub Neruda - Dec 1

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Let's play with C++ reflection

Jakub Neruda - Nov 12

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31
chevron_left
2.2k Points • 141 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
47Posts
40Comments
25Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

View all jobs →

Commenters (This Week)

9 comments
2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!