Bonita Montero
2024-02-13 11:07:14 UTC
If you initialize a function<>-object with a reference_wrapper it
is guaranteed that the function<>-object references an external
function-object without any memory allocation. libstdc++ and libc++
don't allocate any memory with such function<>-objects according
to the standard, but MSVC does allocate external memory.
#include <iostream>
#include <functional>
using namespace std;
void *operator new( size_t n )
{
cout << "alloc" << endl;
void *p = malloc( n );
if( !p )
throw bad_alloc();
return p;
}
void operator delete( void *p )
{
free( p );
}
int main()
{
function<void ()> fn;
string str( "hello word" );
auto lam = [str = str]() { cout << str << endl; };
fn = ref( lam );
fn();
}
is guaranteed that the function<>-object references an external
function-object without any memory allocation. libstdc++ and libc++
don't allocate any memory with such function<>-objects according
to the standard, but MSVC does allocate external memory.
#include <iostream>
#include <functional>
using namespace std;
void *operator new( size_t n )
{
cout << "alloc" << endl;
void *p = malloc( n );
if( !p )
throw bad_alloc();
return p;
}
void operator delete( void *p )
{
free( p );
}
int main()
{
function<void ()> fn;
string str( "hello word" );
auto lam = [str = str]() { cout << str << endl; };
fn = ref( lam );
fn();
}