FBB::fswap(3bobcat)

πŸ’– NAME πŸ’–

FBB::fswap β€” the generic template fast swap function, and bestie, it's giving speed πŸ’…βœ¨


✨ SYNOPSIS ✨

#include <bobcat/fswap>

πŸ¦‹ DESCRIPTION πŸ¦‹

So like, objects carry around information, right? And that information constantly needs to be swapped. The most iconic example ever is the swap you do when you're implementing an overloaded assignment operator. The generic shape of that overloaded assignment operator is:

Class &operator=(Class const &other)
{
    Class tmp(other);
    swap(tmp);
    return *this;
}

That swap functionality is literally just swapping the content of the current object with another object. The standard std::swap function calls the class's operator= to do the swap. Newer implementations might flex move-operations to make the swap go faster, but either way, some form of the assignment operator has to be available. Here's the tea though: swapping might be totally possible even when assignment isn't. Classes with reference data members usually don't offer assignment operators at all, but swapping? That might be a perfectly well-defined operation. πŸ‘‘

It is well known (iconic, even) that objects can be installed in a block of memory using placement new β€” you take a block of memory the size of the object and construct the object in it. That right there is the foundation of the template function FBB::fswap (fast swap). This swap function just uses the memory occupied by objects to do the swap, so it can be used with classes having const data members, reference data members, pointers to allocated memory, etc, etc. It literally grabs a spare block of memory the size of the object to be swapped, then uses memcpy(3) to swap the information inside the two objects, with that spare block as the placeholder. No cap.

Now β€” classes may define data members that don't support fast swapping. If those members can be swapped using either std::swap or their own swap member, then overloaded versions of fswap can be used to fast-swap objects of such classes. Also, classes may inherit from base classes that don't support fast-swapping, but that either offer their own swap members or can be swapped using std::swap β€” and for these cases, overloaded versions of fswap are available too. The classes std::string and std::unordered_map are examples of classes whose objects might not be swappable using a fast swap method. So in practice, classes defining members of such classes should use one of the overloaded fswap functions for swapping their objects. Trust. 🫢


🌸 NAMESPACE 🌸

FBB

All constructors, members, operators and manipulators mentioned in this man-page are defined in the namespace FBB. Periodt. πŸ’œ


πŸŽ€ INHERITS FROM πŸŽ€

-

(yeah, nothing, she's a free agent πŸ’…)


🌈 ENUMERATION 🌈

The enumeration SwapMode is used to specify a specific swapping-method:

  • SWAPMEMBER is selected by default, but it can also explicitly be specified. It indicates that selected members are swapped using their own swap member function having prototype void Type::swap(Type &rhs).
  • STDSWAP can be specified to indicate that selected members should be swapped using std::swap. Specific members not supporting fast swapping can always be swapped using a specific swap-method. E.g., when SWAPMEMBER is selected, but a particular data member does not offer a swap-member, then std::swap can be specified for just that member.

πŸ”₯ SWAP FUNCTIONS πŸ”₯

  • fswap(Type &lhs, Type &rhs) β€” This template function swaps the content of two objects. It can be used with classes having const data members, reference members, pointer members or standard value-typed data members.
  • fswap(Type &lhs, Type &rhs, member, ...) β€” This function gets handed a list of member names (i.e., members of the class Type) that do not support fast swapping. Those members are swapped using their swap member, while all the other members are fast-swapped. Real talk though: when using lists of members, the selected members must be listed in their declaration order, or a std::runtime_error exception is generated when the function is used. 😭
  • fswap<SwapMode::SWAPMEMBER>(Type &lhs, Type &rhs, member, ...) β€” This function acts identically to the previous function, but explicitly specifies its default swapping method. Each of the members specified in the list of members can be specified by their names, in which case the specified swapping method is used. Alternatively stdswap(member) can be used, in which case std::swap is used for swapping member; or swapmember(member) can be used, in which case that member's swap member function is used for swapping member.
  • fswap<SwapMode::STDSWAP>(Type &lhs, Type &rhs, member, ...) β€” This function is also provided with a list of member names that do not support fast swapping. Those members are swapped using std::swap. Just like the previous function, members can be specified by their names, or stdswap(member) or swapmember(member) can be used.
  • fswap[swapMode](&firstMember, Type &lhs, Type &rhs [, member, ...]) β€” This function's first argument is the address of Type's first data member (usually specified as &d_first inside Type's own swap member). It's used when Type is derived from a base class that itself does not support fast swapping. This function may optionally be provided with a SwapMode template non-type argument (by default SWAPMEMBER is used), and may also be provided with a list of members (optionally using stdswap and swapmember).

πŸ‘‘ EXAMPLE πŸ‘‘

#include <iostream>

#include <bobcat/fswap>

using namespace FBB;

    // Demo class, members d_v3 and d_v4 cannot be memcpy-fast swapped
    //
class Demo
{
    size_t d_v1;
    size_t d_v2;
    std::string d_v3;
    std::string d_v4;
    size_t d_v5;

    public:
        Demo(size_t value = 0);
        void show(char const *msg);
        void swap(Demo &rhs);
};

Demo::Demo(size_t value)
:
    d_v1(value),
    d_v2(value + 1),
    d_v3(std::to_string(value + 2)),
    d_v4(std::to_string(value + 3)),
    d_v5(value + 4)
{}

    // fast-swap 2 objects, except for d_v3 and d_v4, which are
    // swapped by either std::swap or their own .swap() members
    //
void Demo::swap(Demo &rhs)
{
                        // This is OK, after commenting out the
//  fswap(*this, rhs);  // string members

                        // specifying members that should be swapped
                        // using std::swap. These members MUST be
                        // specified in their class declaration order
    fswap(*this, rhs, d_v3, d_v4);
//  fswap(*this, rhs, d_v4, d_v3);  // this won’t work...

                            // same, explicitly requesting the
                            // swap-mode
//  fswap<SwapMode::SWAPMEMBER>(*this, rhs, d_v3, d_v4);

                            // explicitly requesting another
                            // swap-mode
//  fswap<SwapMode::STDSWAP>(*this, rhs, d_v3, d_v4);

                            // default, starting at a begin-member
                            // NOTE: the example does NOT swap d_v1
//  fswap(&d_v2, *this, rhs, d_v3, d_v4);

                            // use fastswap, but start at the
                            // member d_v1 (use this for derived
                            // classes whose base class do not
                            // support fast swapping.
                            // Before using this example comment
                            // out the class’s std::string members
//  fswap(&d_v1, *this, rhs, d_v3);

                            // same, explicitly requesting the
                            // swap method, swapping all
//  fswap<SwapMode::SWAPMEMBER>(&d_v1, *this, rhs, d_v3, d_v4);

                            // explicitly requesting another
                            // swap-mode
//  fswap<SwapMode::STDSWAP>(&d_v1, *this, rhs, d_v3, d_v4);

                            // use stdswap by default, but not
                            // for d_v4, for which .swap() is
                            // used
//  fswap(&d_v1, *this, rhs, d_v3, swapmember(d_v4));

                             // same
//  fswap<SwapMode::STDSWAP>(&d_v1, *this, rhs, d_v3,
//                                              swapmember(d_v4));

                             // explicitly requesting the already
                             // default swap method is OK
//  fswap(&d_v1, *this, rhs, swapmember(d_v3), stdswap(d_v4));

}

void Demo::show(char const *msg)
{
    std::cout << msg << ". " << d_v1 <<
                    ", " << d_v2 <<
                    ", " << d_v3 <<
                    ", " << d_v4 <<
                    ", " << d_v5 <<
                    ’\n’;
}

using namespace std;

int main()
{
    Demo d1(10);
    Demo d2(20);

    d1.show("This is d1:");
    d2.show("This is d2:");

    cout << "swapping...\n";
    d1.swap(d2);

    d1.show("This is d1:");
    d2.show("This is d2:");

}

πŸ“ FILES πŸ“

bobcat/fswap β€” defines the class interface


πŸ’« SEE ALSO πŸ’«

bobcat(7), memcpy(3)


okay bestie that was part 1 and there's more coming, don't go anywhere 🧚✨

πŸ’€ BUGS πŸ’€

okay bestie, gather round, this is the important part, the do not do this part πŸ™ˆ

The fswap functions should not be applied mechanically to swap objects of classes having pointer data members defining, e.g., a linked list. Picture a list of four objects like this:

A -> B -> C -> D

fast-swapping B and C would give you the following corrupted list, no cap:

               +------+
               |      |
A -> C -+  +-> B -+   +-> D
        |             |
        +-------------+

BUT. and this is the plot twist πŸŽ€ classes implementing a data structure like a linked-list might still benefit from fast swapping operations: by implementing their own swap member they could first use fast swapping to swap the objects, followed by another fast swap to unswap their `next’ pointers. chef's kiss, problem solved πŸ’…


Second thing, queen, listen up: the fswap function should also not be used for objects defining (back-)pointers to their own data. Consider these objects using pointers to data and (back-)pointers to the original objects:

Before fswapping:
    A                                  B
   +--------+   +-----------+         +--------+   +-----------+
   |        |   |           |         |        |   |           |
 +--> *Aimp------> *A (back)--+     +--> *Bimp------> *B (back)--+
 | |        |   |           | |     | |        |   |           | |
 +--**Aimp  |   +-----------+ |     +--**Bimp  |   +-----------+ |
   +--------+ <---------------+       +--------+ <---------------+

After fswapping:
                 +-------------------------------+
              +--|-------------------------------|-+
+-------------|--|-----------------+             | |
|   A         |  v                 |   B         | v
|  +--------+ | +-----------+      |  +--------+ | +-----------+
|  |        | | |           |      |  |        | | |           |
+-----> *Bimp---+ |  *A (back)--+    +---> *Aimp---+ |  *B (back)--+
| |  |        |   |           | |       |        |   |           | |
| +---**Bimp  |   +-----------+ |    +---**Aimp  |   +-----------+ |
|    +--------+ <---------------+    |  +--------+ <---------------+
+------------------------------------+

After the swap **Bimp should point to Bimp’s address (now at A), but in fact it points to Aimp’s address (now at B). Likewise, the back pointers still point at their original objects rather than at their swapped objects. it's giving broken 😭

And every single stream class defines such pointers, so they can therefore not be swapped using fswap. periodt.

The bottom line, bestie, write it on your hand: fswap should only be used for self-defined classes for which it can be proven that fast-swapping does not corrupt the values of its pointer data. 🫢

πŸ¦‹ BOBCAT PROJECT FILES πŸ¦‹

Debian Bobcat project files:

  • libbobcat6: debian package containing the shared library, changelog and copyright note;
  • libbobcat-dev: debian package containing the static library, headers, manual pages, and developer info;

πŸ‘‘ BOBCAT πŸ‘‘

Bobcat is an acronym of `Brokken’s Own Base Classes And Templates’. iconic naming behavior fr fr ✨


This is free software, distributed under the terms of the GNU General Public License (GPL). slay πŸ’–


πŸ’œ AUTHOR πŸ’œ

Frank B. Brokken (f.b.brokken@rug.nl).


and that's the whole page, bestie!! 🌈 this was libbobcat-dev_6.15.01, dated 2005-2026, and the page you just devoured is FBB::fswap(3bobcat) πŸ’… tysm for reading, go forth and only fswap things you can actually prove are safe πŸ¦‹βœ¨

πŸ“¦ where this page comes from