Provide a simple to use swap
algorithm.
More...
Detailed Description
- Outline
-
-
- Purpose:
- Provide a simple to use
swap
algorithm.
-
- Classes:
-
- See also:
- bsl_algorithm
-
- Description:
- This component provides a namespace for a utility function that swaps the value of two objects of the same type. Using this utility is intended to be a simpler alternative to using the standard
swap
algorithm directly. The standard swap
algorithm is provided in the bsl
namespace in a generic form and overloaded for specific classes in the namespaces of those classes. When the swap
algorithm is used, its specific implementation is supposed to be found by Argument Dependent Lookup (ADL). Finding the proper swap
function with ADL requires bringing the bsl::swap
into the current scope with the using
directive and then calling a swap
function without the namespace qualification. The swap
utility static function provided by this component relieves the end-user from a need to remember those details of the proper usage of the swap
algorithm.
-
- Usage:
- This section illustrates intended use of this component.
-
- Example 1: Using bslalg::SwapUtil::swap:
- In this example we define a type
Container
and use bslalg::SwapUtil
to both implement a user-defined swap
for Container
, and swap two container objects.
- We start by defining a class
Container
in the xyz
namespace. Further we assume that Container
has some expensive-to-copy data, so we provide a custom swap
algorithm to efficiently swap the data between a two objects this class by defining a swap
method and a swap
free function. namespace xyz {
class Container {
private:
int d_expensiveData;
public:
void swap(Container& other);
};
void swap(Container& a, Container& b);
Note that the free function swap
is overloaded in the namespace of the class Container
, which is xyz
.
- Next, we implemented the
swap
method using the bslalg::SwapUtil::swap
to swap the individual data elements: Notice that calling bslalg::SwapUtil::swap
is equivalent to making the bsl::swap
available in the current scope by doing using bsl::swap
and making a subsequent call to an unqualified swap
function.
- Then, we implement the
swap
free function: inline
void swap(Container& a, Container& b)
{
a.swap(b);
}
}
Finally we can use bslalg::SwapUtil::swap
to swap two objects of class xyz::Container
: The above code correctly calls the xyz::swap
overload for the Container
class.