Sujet : Re: Opinions on `defer`?
De : Bonita.Montero (at) *nospam* gmail.com (Bonita Montero)
Groupes : comp.lang.cDate : 07. Jan 2025, 19:17:51
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vljr4f$2aqdb$1@raubtier-asyl.eternal-september.org>
References : 1
User-Agent : Mozilla Thunderbird
Am 07.01.2025 um 01:35 schrieb Alexis:
Hi all,
"Modern C" author Jens Gustedt has been posting on his blog about a
proposed `defer` feature (as provided by e.g. Zig and Go), the most
recent being:
https://gustedt.wordpress.com/2025/01/06/simple-defer-ready-to-use/
What do people here think about having such a feature in C?
That doesn’t save this hopelessly outdated programming language either.
When I dont't have a RAII-class for a special purpose in C++ I use my
class invoke_on_destruct:
#pragma once
#include <utility>
template<typename Fn>
struct invoke_on_destruct;
struct iod_base
{
private:
template<typename Fn>
friend struct invoke_on_destruct;
bool m_enabled;
iod_base *m_next;
iod_base( iod_base *next ) :
m_enabled( true ),
m_next( next )
{
}
iod_base( iod_base const & ) = default;
iod_base( iod_base && ) = default;
void disable()
{
m_enabled = false;
}
};
template<typename Fn>
struct invoke_on_destruct final : public iod_base
{
private:
Fn m_fn;
public:
invoke_on_destruct( Fn &&fn, iod_base *next = nullptr )
requires requires( Fn fn ) { { fn() }; } :
iod_base( next ),
m_fn( std::forward<Fn>( fn ) )
{
}
invoke_on_destruct( invoke_on_destruct const & ) = default;
invoke_on_destruct( invoke_on_destruct && ) = default;
~invoke_on_destruct()
{
bool enabled = m_enabled;
if( m_next )
m_next->m_enabled = enabled;
if( enabled )
m_fn();
}
void operator ()()
{
m_enabled = false;
m_fn();
}
using iod_base::disable;
};
Simply use like that;
void *p = ...
invoke_on_destruct iod( [&] { deallocate( p ); } );