[Bug libstdc++/97912] New: Get rid of location-invariant requirement in std::function small object optimisation

redi at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Thu Nov 19 17:29:17 GMT 2020


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=97912

            Bug ID: 97912
           Summary: Get rid of location-invariant requirement in
                    std::function small object optimisation
           Product: gcc
           Version: 11.0
            Status: UNCONFIRMED
          Severity: enhancement
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: redi at gcc dot gnu.org
                CC: barry.revzin at gmail dot com
  Target Milestone: ---

std::function will only store the target object in an internal buffer (rather
than on the heap) if it is "location invariant", which means trivially
copyable.

It would be good to remove the trivially copyable requirement, and store any
type of suitable size and alignment to fit in the buffer.

The difficulty is that std::function::swap does a byte-wise copy of the
_Any_data buffer, which is why we require trivially copyable. Changing that
might be an ABI break (existing code will have inlined that function::swap
definition, and will still do a byte-wise copy rather than whatever the new
code does to support non-trivially copyable types).

This testcase fails if we remove the trivially copyable requirement:

#include <functional>
#include <cassert>

struct selfobsessed
{
  selfobsessed() : me(this) { }

  selfobsessed(const selfobsessed&) : me(this) { }
  selfobsessed& operator=(const selfobsessed&) { return *this; }

  void operator()() const { assert(me == this); }

  selfobsessed* me;
};

int main()
{
  std::function<void()> f1( selfobsessed{} );
  std::function<void()> f2;
  swap(f1, f2);
  f2();
}


More information about the Gcc-bugs mailing list