Tuesday Coding Tip 17 — Wrapping C APIs

2 5 32
calendar_today agoschedule1 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
}
Part 5 of 5 in Tuesday Coding Tips
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21

Tuesday Coding Tip 15 — Mathematical constants in C++

Jakub Neruda - Jun 9
chevron_left
942 Points39 Badges
Brno, Czech Republiclinkedin.com/in/jakub-neruda
23Posts
10Comments
9Connections
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)

4 comments
3 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!