Sunday 15 July 2018

rvalue

int& ref = 9;   
we get an error: "invalid initialization of non-const reference of type int& from an rvalue of type int
We can only do:
int nine = 9;
int& ref = nine;
Here is an example of rvalue reference
int&& rvalue_ref = 99;
#include 

void f(int& i) { std::cout << "lvalue ref: " << i << "\n"; }
void f(int&& i) { std::cout << "rvalue ref: " << i << "\n"; }

int main()
{
    int i = 77;
    f(i);    // lvalue ref called
    f(99);   // rvalue ref called

    f(std::move(i));  // rvalue ref called

    return 0;
}
The main usage of rvalue references is to create a move constructor and move assignment operator. A move constructor, like a copy constructor, takes an instance of an object as its argument and creates a new instance from original object.

Move Constructor
In its the simplest form, a move constructor looks like this:
A(A&& other) noexcept    // C++11 - specifying non-exception throwing functions
{
  mData =  other.mData;  // shallow copy or referential copy
  other.mData = nullptr;
}
Note that it doesn't allocate any new resources and contents are moved not copied: what was in other moved to a new member, and what was in other disappeared.
Suppose that address is pointing to an array which has millions of integer. We do not copy the elements. We do not create anything. We just move it. If we use old copy constructor for a class which has an 1-million element array member, we may have that many assignment operations, which is costly. Now, with the move constructor, we can save a lot.
// Move constructor.
A(A&& other) : mData(NULL), mLength(0)
{
    // Copy the data pointer and its length from the 
    // source object.
    mData = other.mData;
    mLength = other.mLength;

    // Release the data pointer from the source object so that
    // the destructor does not free the memory multiple times.
    other.mData = NULL;
    other.mLength = 0;
}
The move constructor is much faster than a copy constructor because it doesn't allocate memory nor does it copy memory blocks.



No comments:

Post a Comment