concept temporary in category c++

appears as: temporaries, temporary
Functional Programming in C++

This is an excerpt from Manning's book Functional Programming in C++.

The forwarding reference allows you to accept both const and non-const objects, and temporaries. Now you only need to pass that argument, and pass it in the same value category as you’ve received it, which is exactly what std::forward does.

You’ll construct two separate instances of person_t and copy all the data that person_t holds twice, whereas you want to create only a single person—to assign to the new_person variable. It would be better if you could avoid this by detecting that .with_surname has been called on a temporary object, and that you don’t need to create a copy of it, but you can move the data from it into the result. Fortunately, you can do this by creating two separate functions for each of .with_name and .with_surname—one that works on proper values, and one for temporaries.

Listing 5.9 Separating member functions for normal values and temporaries
class person_t {
public:
    person_t with_name(const std::string& name) const &     #1  
    {
        person_t result(*this);    #2  

        result.m_name = name;    #3  

        return result;    #4  
    }

    person_t with_name(const std::string& name) &&          #5  
    {
        person_t result(std::move(*this));    #6  

        result.m_name = name;    #7  

        return result;    #8  
    }

};

#1   This member function will work on normal values and lvalue references.
#2   Creates a copy of the person
#3   Sets the new name for that person. It’s OK to change the name because this person_t instance still isn’t visible from the outside world.
#4   Returns the newly created person_t instance. From this point on, it’s immutable.
#5   This one will be called on temporaries and other rvalue references.
#6   Calls the move constructor instead of the copy constructor
#7   Sets the name
#8   Returns the newly created person


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":2,\"ch\":48},{\"line\":2,\"ch\":55}],[{\"line\":11,\"ch\":48},{\"line\":11,\"ch\":50}]]"}
!@%STYLE%@!