mardi 31 mars 2015

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.


Aucun commentaire:

Enregistrer un commentaire