Rajeshwar
Rajeshwar

Reputation: 11651

Passing a temporary as a reference

I am currently trying to understand the copy and swap idiom through this post. The answer posted has the following code in it

class dumb_array
{
public:
    // ...

    friend void swap(dumb_array& first, dumb_array& second) // nothrow
    {
        // enable ADL (not necessary in our case, but good practice)
        using std::swap; 

        // by swapping the members of two classes,
        // the two classes are effectively swapped
        swap(first.mSize, second.mSize); 
        swap(first.mArray, second.mArray);
    }

    // move constructor
    dumb_array(dumb_array&& other)
        : dumb_array() // initialize via default constructor, C++11 only
    {
        swap(*this, other); //<------Question about this statement
    }

    // ...
};

I noticed that the author used this statement

swap(*this, other);

other is a temporary or a rvalue which is being passed as a reference to the method swap. I was not sure if we could pass a rvalue by reference. In order to test this I tried doing this however the following does not work until i convert the parameter to a const reference

void myfunct(std::string& f)
{
    std::cout << "Hello";
}

int main() 
{
   myfunct(std::string("dsdsd"));
}

My question is how can other being a temporary be passed by reference in swap(*this, other); while myfunct(std::string("dsdsd")); cant be passed by reference.

Upvotes: 0

Views: 161

Answers (2)

Adam Leggett
Adam Leggett

Reputation: 4113

In the case of:

myfunct(std::string("dsdsd"));

The value std::string("dsdsd") is a temporary within a scope that the call to myfunct() is actually outside of.

C++ explicitly specifies that binding the reference to const extends the lifetime of the temporary to the lifetime of the reference itself.

Upvotes: 0

Jarod42
Jarod42

Reputation: 217145

The constructor takes a rvalue reference, but other is a lvalue (it has a name).

Upvotes: 7

Related Questions