Skip to content

[libc++] std::function with small object optimization copies instead of moves #132139

@BenjaminSchaaf

Description

@BenjaminSchaaf

When using std::function I noticed that sometimes the captured data is copied even if the std::function is only ever moved.

I've tracked this down to the following code:

__f_ = __as_base(&__buf_);

It looks like when the small object optimization is in use for std::function, then the captured data is copied instead of moved whenever the function is moved. In extreme cases this could result in massively more work being done.

The issue reproduces trivially, see godbolt: https://godbolt.org/z/czTev8jfc

Note that the captured data needs to be < 3*sizeof(void *) and have noexcept on its copy constructor to trigger the small object optimization. When that's the case the data is copied instead of moved.

Metadata

Metadata

Assignees

No one assigned

    Labels

    duplicateResolved as duplicatelibc++libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions