Skip to content
C++Tipsand other shenanigans

Tips

Tips and tricks that didn't fill a proper long-form article

01

Safely interfacing with C-style factories

Consider a factory function which creates a widget at the end of a double pointer:

void create_widget(Widget** ptr);

Being a good C++ developer, you want to manage your Widgets with smart pointers. This means that you need to do a little dance to set up the ownership:

std::unique_ptr<Widget> ptr();
// Needs a separate variable otherwise we try to take the address of an rvalue
Widget* raw_ptr = nullptr;
create_widget(&raw_ptr);
ptr.reset(raw_ptr); // Forget this and we leak

C++23 gives you a better way to do this, with std::out_ptr.

Read more
02

Are your maps allocating unnecessarily?

Consider a map with a std::string as the key type, for example mapping an HTTP route to its handler:

std::unordered_map<std::string, Handler const*> handlers;

What actually happens when you try to look things up in this map? Let’s say that you want to test it with handlers.find("/api/v2/accounts/positions/summary"). This code will compile and run quite happily, but under the hood this allocates the literal into an entirely new std::string object, hashes it, finds the value, and then throws the temporary string away.

Read more
03

Can you subscript tuples?

In C++ tuples are implemented as library feature rather than as language feature. As a consequence of that, we are syntactically limited by what the language offers.

This means rather than being able to subscript tuples directly, we need to use std::get<N>(tup) instead.

So… if we step a bit outside of the boundaries of the standard, can we subscript instead?

auto tup = nonstd::tuple(1, 'c', 3.2);
f(tup[0], tup[2]);
Read more
04

Your compiler complains you're not in template context?

This can happen if you attempt to use P1061 pack-introducing structured bindings outside of a template:

void f() {
// error: pack declaration outside of template
auto [...Is] = expr;
}

To avoid turning f itself into a template, you can use P1306 expansion statements. Unlike lambda solutions, this does not push another function scope.

Read more
PydongWrong language? How about Python shenanigans instead?