Object-Oriented Programming: Move Semantics in C++

We have talked about references before, and explained them in detail.  We have also mentioned a concept called "lvalues".  An lvalue in C++ is something which can be assigned to.  It persists beyond a single expression.  All variables are lvalues.  Rvalues, on the other hand, are temporary values which do not exist beyond the expression that uses them.  Obviously, they cannot be assigned to.  For example:

a + (b * c); //the value of b*c is an rvalue, a temporary value; it will be stored somewhere until it's added to a;
             //after that, it won't exist anymore

 

However, C++11 introduced a new concept which combines rvalues with something we already know very well - the copy constructor and the assignment operator.  This new feature is called move semantics.  The first step in understanding move semantics is explaining rvalue references (note that this is only possible in C++11 and newer versions).  As the name says, rvalue references are references to rvalues (in contrast to the references we've talked about before, which were lvalue references).  Here is how you declare an rvalue reference:

type&& rvRef;
But why is this important?  Why would you want to use an rvalue reference?  Consider the following code:
MyClass c(a + b); //a+b is an rvalue, which makes this line equal to:

MyClass c(temp); //this activates the copy constructor

We can see that the copy constructor was called.  This is a common situation, and we have explained it before, when we learned how to write a copy constructor.  However, in situations like this one, we do not want to perform a copy operation.  A faster and more suitable alternative would be a move operation - we just want to copy the data and then "nullify" the source, without creating a deep copy.  It's okay to do this because the client has no way of inspecting the source object again anyway - since it was an rvalue.

 

This brings us to the following conclusion: in addition to the copy constructor, destructor and the overloaded assignment operator, we should also write the move constructor and overload the move assignment operator.

MyClass(MyClass&&);

MyClass& operator=(MyClass&&);

 

Below is an example:

class ArrayClass
{
private:

int *array;

public:

ArrayClass();
ArrayClass(const ArrayClass&);
ArrayClass& operator=(ArrayClass&);
~ArrayClass();
/*move constructor*/
ArrayClass(ArrayClass&&);
/*move assignment operator*/
ArrayClass& operator=(ArrayClass&&);
};

ArrayClass::ArrayClass(ArrayClass&& other)
{
this->array = other->array;
other->array = nullptr;
}
Since we have already learned how the assigment operator is overloaded (the code is similar to that of the copy constructor), we leave it to the reader to implement the move assignment operator as an exercise.

 

Thought For The Day


“It seems reasonable to envision, for a time 10 or 15 years hence, a “thinking center” that will incorporate the functions of present-day libraries together with anticipated advances in information storage and retrieval and ... a network of such centers, connected to one another by wide-band communication lines and to individual users by leased-wire services.”
J. C. R. Licklider

 

5 Companies with Great Perks

If your 9-5 job is more tedious than inspirational, it might be time for you to move on.  Wondering where to work next?  Check out these 5 companies with amazing perks--you might just be motivated to update your resume:

  1. Google.  Located in Mountain View, California, Google isn’t just a place to work, it’s practically a recreation center.  The company offers free lunches and dinners, oil changes, car washes, massages, yoga, a play room, and $12,000/year in tuition assistance.

  2. Akraya.  Hate to clean?  Akraya may be the perfect employer for you.  This Santa Clara, California IT staffing firm sends professional cleaners to employees’ homes every 2 weeks.

  3. Epic Systems.  Madison, Wisconsin-based healthcare tech company Epic Systems generously offers employees monthlong paid vacations!  And, if employees decide to go on a sabbatical to a country they’ve never been to before, the company pays the majority of travel costs for the employee and a friend.  Almost as exciting, their campus offers “an Indiana Jones-themed tunnel, a tree-house conference room, a moat, and plenty of green space for outdoor activities,” reports Business Insider.

  4. Zappos.  Zappos might even make Google look like hard labor!  According to themuse, “the Zappos headquarters in downtown Las Vegas includes a bistro, coffee shop, yoga studio, nap room, gym, backyard, rooftop deck, hammocks, ping-pong, a beach-themed conference room, ‘penthouse’ co-working spaces, and (drumroll, please) touch-screen video games in the elevators.”  The company also keeps things lively with parades, themed events, picnics, live animals, trivia nights, pajama days, karaoke, and sledding!

  5. Chesapeake Energy.  Love to work out?  Chesapeake Energy may be a great fit.  The natural gas producer offers an indoor rock-climbing wall and an on-site, 72,000-square-foot fitness center which includes a sand volleyball court and an Olympic-sized swimming pool.

Object-Oriented Programming: Overloading the Bitshift Operators

The bitshift operators << and >> can also be overloaded in C++.  However, their purpose often isn't performing the actual shifting.  They are commonly used as stream operators, for output and input, respectively.  We already know how to write something to the standard output:

std::cout << "Output";
In many situations, you will want objects of your class to be printed on the console or to a file in a certain format.  You can do that by overloading the << operator.  The same goes for input and the >> operator.

 

There is one special thing about overloading the bitshift operators: they can't be overloaded as member functions, which means that they are usually overloaded as friend functions.  Why?  Let's see the code of the overloaded << operator, and the answer will become clear. (Overloading the input operator is analogous).

class Complex
{
    ...
    friend std::ostream& operator<<(std::ostream&, const Complex&);
};

std::ostream& operator<<(std::ostream &out, const Complex &c)
{
    out << "(" << c.re << "," << c.im << ")" << endl;
    return out;
}
As you can see, when you use a stream operator, the first parameter is a stream.  Since you do not have access to the stream object (it's not yours to modify), this can not be a member function.  That is why we are overloading it as friend (so that it can have access to private members of our Complex class).
Note: A reference to a stream object is returned so that you can chain stream operations together.

 

Now, you have provided a way for Complex objects to be printed.  You can use the overloaded operator like this:

int main()
{
    Complex c1;
    cout << c1;
    return 0;
}
As we said, overloading the input operator is analogous (it is also overloaded as friend), and this is what it looks like:
std::istream& operator>>(std::istream  &in, const Complex &c)
{ 
    in >> c.re >> c.im;
    return in;            
}

 

Are You in Need of A Celebration? 5 Unusual March Holidays

The stretch between President’s Day and Memorial Day can seem like a long one if you live for work holidays. Unfortunately, while we can’t guarantee you’ll get these days off at the office, we thought we’d liven up your mood by sharing with you 5 of the more unusual holidays that take place in March:

1. Thursday, March 3rd – I Want You to Be Happy Day

While the origins of this day are uncertain, the premise behind it is simple.  This is a day about making others feel good.  Send your spouse flowers, thank a coworker, or make yourself happy by taking a hooky day from work!

2. Monday, March 14th – National Potato Chip Day

Have you given up on your New Year’s Resolution? Don’t get depressed.  Eat a bag of chips on National Potato Chip Day and begin working on your summer body tomorrow instead.

3. Wednesday, March 16 th – Everything You Do Is Right Day

This is a day focused on feeling good about everything you do.  Consider it your “free pass.”  Call in late to work, burp at the dinner table, and be as argumentative as you like—you can’t lose today.  However, an important caveat—the legal system is unlikely to give you a pass if you behave too hedonistically!

4. Tuesday, March 22nd – International Goof Off Day

Play a round of golf, watch videos, or simply read a book—this day was made for you.  International Goof Off Day is about relaxing and enjoying yourself, rather than keeping your nose to the grindstone.

5. Saturday, March 26th – Make Up Your Own Holiday Day

Don’t find any of the above holidays appealing?  Make up your own!  This is a day for creating your own celebration.  So, get your friends together and use this as an opportunity to celebrate something really unusual.  We suspect that this was the day that gave birth to International Talk Like A Pirate Day, celebrated on September 19th