How it works...

In this example, we will look at what a reference qualified member function is. To explain what a reference-qualified member function is, let's look at the following example:

#include <iostream>

class the_answer
{
public:

~the_answer() = default;

void foo() &
{
std::cout << "the answer is: 42 ";
}

void foo() &&
{
std::cout << "the answer is not: 0 ";
}

public:

the_answer(the_answer &&other) noexcept = default;
the_answer &operator=(the_answer &&other) noexcept = default;

the_answer(const the_answer &other) = default;
the_answer &operator=(const the_answer &other) = default;
};

In this example, we have implemented a foo() function, but we have two different versions. The first version has & at the end while the second has && at the end. Which foo() function gets executed is dictated by whether or not the instance is an l-value or an r-value, as in the following example:

int main(void)
{
the_answer is;

is.foo();
std::move(is).foo();
the_answer{}.foo();
}

This results in the following when executed:

As shown in the preceding example, the first execution of foo() is an l-value, as the l-value version of foo() is executed (that is, the function with & at the end). The last two executions of foo() are r-values as the r-value versions of foo() are executed.

Reference-qualified member functions can be used to ensure that the function is only called in the right context. Another reason to use these types of functions is to ensure that the function is only called when an l-value or r-value reference exists.

For example, you might not want to allow foo() to be called as an r-value as this type of invocation doesn't ensure that an instance of the class actually has a lifetime outside of the call itself, as demonstrated in the preceding example.

In the next recipe, we will learn how to make a class that can neither be moved nor copied, and explain why you might do such a thing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset