TechWire

Category - Tips & Tricks

The perfect swap in C++

So you are coding this cool app and you need to swap two variables. How does a good programmer do that in C++? The STL (Standard Templates Library) provides the std::swap function which does exactly what we want.

[code language=”cpp”]int a = 10;
int b = 12;
std::swap(a, b);[/code]

That’s easy. But hey, why don’t we go ahead and see actually what std::swap does behind the scenes? A grep in the Apache STL implementation gives us:

[code language=”cpp”]template <class _TypeT>
inline void swap (_TypeT& __a, _TypeT& __b)
{
   _TypeT __tmp = __a;
   __a = __b;
  __b = __tmp;
}[/code]

Woah, all the underscores! But don’t panic just yet. All it does is the grade-school swapping:

[code language=”cpp”]T tmp = a;
a = b;
b = tmp;[/code]

Hmm. That is perhaps the most straight-forward swap implementation. But how does it perform? Look again.

[code language=”cpp”]T tmp = a; // a copy of ‘a’ is created
a = b;  // a copy of ‘b’ is created
b = tmp;  // a copy of ‘tmp’ is created[/code]

That’s a lot of copies for a simple function! What if we could just ‘swap’ the two values without copying?

We google around a bit and find out that the above std::swap implementation is actually the old way of doing things. The new C++11 implementations does this differently. So we check the C++11 include files.

[code language=”cpp”]template<typename _Tp>
  inline void
swap(_Tp& __a, _Tp& __b)
   {
   _Tp __tmp = _GLIBCXX_MOVE(__a);
  __a = _GLIBCXX_MOVE(__b);
   __b = _GLIBCXX_MOVE(__tmp);
  }[/code]

That’s more confusing than the previous one. Again, don’t panic. We can simplify the things. _GLIBCXX_MOVE is defined to be std::move. Let’s just call it ‘move’. So the above function is roughly similar to:

[code language=”cpp”]T tmp = move(a);
a = move(b);
b = move(tmp);[/code]

Now we are scratching our chins. At first glance, the implementation looks much similar to the grade-school swap. And then, there’s this move-thingy. Okay, looking back, we remember that the elements were ‘copied’ in the grade-school algorithm. Instead, it looks like the variables are ‘moved’ here.

And we are right! In the first line, tmp is set to the value of a, while the variable a is (temporarily) invalidated. No copying is done. The previous memory location of a is now the territory of tmp. In the next line, a is set to the value of b, while b is invalidated. Finally, b is set to the value of tmp, and tmp itself is invalidated, which we don’t need again anyway. And the result? The two values are swapped without any copy operations!

How does this moving really work? C++11 introduces the so called “rvalue references”. The ‘move’ function returns the rvalue of the input parameter without triggering a copy construction.

[code language=”cpp”]T &a = x; // normal (lvalue) reference
T &&b = y; // rvalue reference [/code]

A full description will not fit in this post, but you can go through this nice little introduction on rvalue references. You might also want to refresh your memory about lvalues and rvalues.

And let’s call it a day and meet again with another little C++ adventure.

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2027.html

Auto-matic typing in C++

C++ is a statically typed language by design. In other words, you have to specify which data type your dear variable is supposed to be. If you declare myCoolVar to be an integer, you can’t let him play with his string friends. Type checking is done at the compile time. So myCoolVar will soon be caught red-handed if it goes matchmaking with a string or a vector.

This is contrast to the radical kids in the block like Python and Ruby who don’t care whom their variables play with. They call themselves dynamically-typed. A washed up floating point might become a variable with a character in a few moments.

Cool as it may sound, dynamic typing is not for everyone. C++ is mostly used where performance and reliability are key factors. Thus the C++ standard has always insisted on strong, static typing. But even if you haven’t been programming since the dinosaurs roamed the earth, you may know that it’s not always easy to remember and explicitly declare the correct variable type. The new C++ standard, or C++11  as it’s known, aims to change this.

C++11 isn’t exactly new to the city. Most compilers around, including gcc and Microsoft C++ compilers, now include support for C++11. Among the dozens of improvements it has brought, let’s have a look at the auto keyword.

Suppose you want to take the length of a C++ string called myStr. Easy-peasy. myStr.length() is the way to go. But wait. The return value of the length() function is string::size_t. Besides from being hard to type in, it’s not easy to remember all these return types either. That’s when the auto keyword comes handy. Instead of,

[code language=”cpp”]string::size_t len = myStr.length();[/code]

you can simply write

[code language=”cpp”]auto len = myStr.length();[/code]

The compiler detects the return type of myStr.length() and makes len a variable of that type. So very convenient.

Not convinced? Suppose you have a map of objects that you need to iterate. How do you initialize the iterator?

[code language=”cpp”]std::map<char,int>::iterator it = myMap.begin();[/code]

Ugh. That isn’t the nicest code snippet you’ve written. But hey, we have our friend auto:

[code language=”cpp”]auto it = myMap.begin();[/code]

Skadoosh! Auto has automagically made it an std::map<char,int>::iterator, because that’s the return type of myMap.begin()! Now that does look nice.

What if I want to declare a variable with a default value?

Suppose you want to declare a variable that holds the length of a string. But you first need to set it to zero.

[code language=”cpp”]auto len = 0;[/code]

Ha! That is wrong! This would make len an int, not string::size_t. But C++11 has an answer for that as well. You can use the decltype keyword like this:

[code language=”cpp”]decltype(myStr.size()) len = 0;[/code]

This declares len as a variable of type returned by myStr.size(), but still initializes it to zero.

Is this dynamic typing?

No, not really. Even though it appears as if auto changes a variable’s type dynamically, it actually happens during the compile time. It’s just that you don’t have to explicitly code the type of the variable, the compiler does that for yourself. Which is mighty sweet of C++11.

Is it safe to use auto?

Isn’t letting your variables roam free considered as bad parenting? No. Not only is it safe to use auto in your C++ code, it’s even recommended that you use it wherever possible. Bjarne Stroustrup, the creator of the C++ language himself, advocates its use. Just make sure that your compiler is updated to support C++11.

Image Credits : http://geekandpoke.typepad.com/geekandpoke/2010/01/best-of-both-worlds.html

10 Bad Tech habits to break in 2013

1. Using your phone while driving – It maybe to take a call, even worse type or read a SMS but using your phone while driving is far worse than a bad habit, it is a deadly habit. Why take the risk? Pull over, take the call and then resume your journey. You can also use a Bluetooth headset which auto connects the calls.

2. Not putting your phone on silent – how many times has a sudden ringing phone completely distracted everyone during a meeting, a religious sermon, at the movie theatre or hospital. It only takes a couple of seconds, make sure you do it.

3. Having weak passwords – With the numerous online services used these days, we tend either to have the same password or simple passwords. Don’t wait till someone hacks into your account, use complex, different passwords for your critical accounts. For non vital services you can have one complex password. Or you can always try a password manager software such as Lastpass or Dashlane but make sure you dont forget the primary password.

4. Not backing up your data – Everyone has their precious data that they would hate losing. It could be your child’s photos, or your business financial data or even maybe your degree assignments. Even knowing the importance of the documents we still fail to backup to a portable or virtual drive. Take 10 minutes to backup your files to dropbox or google drive today. Dont wait till it’s too late

5. Using your laptop on the bed – When you keep the laptop on the bed, the air ventilators get blocked and will lead to the laptop overheating. This could be damaging to your laptop, even worse it could start a fire on your bed.

6. Getting hooked to too many TV series – There are so many interesting and addictive TV series, that you find it hard to choose which one to watch. However following too many of them will eat up a lot of your time. Better keep yourself limited to one or two TV series at the most. Also avoid watching multiple episodes at a stretch. Remember life is short, don’t waste it on loads of TV series.

7. Not properly shutting down your laptop Many a time when we are in a hurry we just snap the lid on the laptop and takeoff. Sometimes closing the lid will not result in your laptop going to Sleep mode. Moving around with an operational hard disk is obviously not good. Take a few seconds to manually initiate the sleep mode. Also remember to properly shutdown your PC from time to time as I am sure it would like to have a regular break.

8. Ignoring privacy settings – It is reported that 25% of facebook users still ignore the privacy setting. If you don’t lock your door intruders will come and steal your data. Keep your personal data private by properly configuring those privacy settings.

9. Using your phone/tablet at inappropriate times – we all know that we love to use the smartphone all the time, but there are instances when u flat out shouldn’t. You might be having meals with the family, having a meetup with friends, or on a date. In these instances please keep your phone aside, it is there to connect with people not to disconnect with them.

10. Keeping your tech gadgets unclean – In a recent study, researchers found over 500 types of bacteria on mobile phones, keyboards, mouse and desktops. Take a wet wipe and clean those dirty gadgets once a week. If once a week is not possible try starting to do it atleast once a month.

8 Useful Google Chrome shortcuts

With time we spend online ever increasing, it is useful to know shortcuts that will make your browsing experience better. Below i have listed 8 useful shortcuts for the Google chrome browser that many people are unaware of. Check them out and save time and clicks, while you can also impress friends and colleagues with them.

Chrome Shortcuts