Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

MSVC-bug

66 views
Skip to first unread message

Bonita Montero

unread,
Feb 13, 2024, 6:07:26 AMFeb 13
to
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();
}

Paavo Helde

unread,
Feb 15, 2024, 8:34:48 AMFeb 15
to
13.02.2024 13:07 Bonita Montero kirjutas:
> 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.

Cannot confirm that. MSVC++ 2022 x64 Release mode does not print "alloc"
at all for this program. In Debug mode there are a couple of allocs, but
these seem to be related to some std::string internals, not the
reference wrapper.

Bonita Montero

unread,
Feb 15, 2024, 10:28:21 AMFeb 15
to
Am 15.02.2024 um 14:34 schrieb Paavo Helde:

> Cannot confirm that. MSVC++ 2022 x64 Release mode does not print "alloc"
> at all for this program. In Debug mode there are a couple of allocs, but
> these seem to be related to some std::string internals, not the
> reference wrapper.

Sorry, I relied on the Debug build.
With Release build there are no allocations.
But I think the Debug build should also be up to the standard.

Paavo Helde

unread,
Feb 15, 2024, 5:11:32 PMFeb 15
to
Constructing and copying std::strings is allowed to allocate dynamic
memory. Make your string a bit longer and you will see allocations also
in Release builds.

Bonita Montero

unread,
Feb 16, 2024, 3:17:29 AMFeb 16
to
Am 15.02.2024 um 23:11 schrieb Paavo Helde:

> Constructing and copying std::strings is allowed to allocate dynamic
> memory. Make your string a bit longer and you will see allocations
> also in Release builds.

The small string optimization is nothing which is guaranteed.
Initializing a function object with a reference_wrapper is
guaranteed to be without memory allocation.

0 new messages