std::swap(std::function)(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

std::swap(std::function)(3) πŸ’…

okay so this page is from the C++ Standard Libary manual β€” that's the manual name, spelling and all, no cap β€” and it's all about the std::swap overload for std::function. Bestie, it's literally a swap for your polymorphic function wrappers. 🫢


✨ NAME ✨

std::swap(std::function) - std::swap(std::function)

(yes, the name section is giving minimalist icon behavior. we respect it. πŸ’…)

🌸 Synopsis 🌸

Defined in header <functional>

template< class R, class... Args >
void swap( std::function<R(Args...)>& lhs, std::function<R(Args...)>&
rhs ) noexcept;

(since C++11) ✨

Overloads the std::swap algorithm for std::function. Exchanges the state of lhs with that of rhs. Effectively calls lhs.swap(rhs).

πŸ’– Parameters πŸ’–

  • lhs, rhs β€” polymorphic function wrappers whose states to swap

πŸŽ€ Return value πŸŽ€

(none) β€” literally nothing, not a single value, it's giving void energy. 🫢

🎬 Example 🎬

// Run this code

#include <functional>
#include <iostream>

void foo(const char* str, int x)
{
    std::cout << "foo(\"" << str << "\", " << x << ")\n";
}

void bar(const char* str, int x)
{
    std::cout << "bar(\"" << str << "\", " << x << ")\n";
}

int main()
{
    std::function<void(const char*, int)> f1{foo};
    std::function<void(const char*, int)> f2{bar};

    f1("f1", 1);
    f2("f2", 2);

    std::cout << "std::swap(f1, f2);\n";
    std::swap(f1, f2);

    f1("f1", 1);
    f2("f2", 2);
}

πŸ–₯️ Output πŸ–₯️

foo("f1", 1)
bar("f2", 2)
std::swap(f1, f2);
bar("f1", 1)
foo("f2", 2)

πŸ’€ Defect reports πŸ’€

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

  • DR LWG 2062 Β· Applied to C++11 Β· Behavior as published: overload of swap for function was not required to be noexcept Β· Correct behavior: required

πŸ‘‘ See also πŸ‘‘

  • swap β€” swaps the contents (public member function)
  • swap(std::move_only_function) (C++23) β€” overloads the std::swap algorithm (function)

source: http://cppreference.com Β· version/date: 2024.06.10 Β· page: std::swap(std::function)(3) πŸ’–βœ¨

πŸ“¦ where this page comes from