A Ruby Crash Course: Day 2

Day 2 of my foray in to Ruby. Today I will look a little deeper into the language.

tl;dr

A quick run through of operators and assignments.

More Basics – Assignment

You can perform multiple assignments. Assigning a list is:

irb(main):001:0> x = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> x
=> [1, 2, 3]

But declaring more than one variable, assigns each one a value:

irb(main):003:0> x,y,z = [1,2,3]
=> [1, 2, 3]
irb(main):004:0> x
=> 1
irb(main):005:0> y
=> 2
irb(main):006:0> z
=> 3

Square braces are optional:

irb(main):014:0> a,b = 1,2,3
=> [1, 2, 3]
irb(main):015:0> a
=> 1
irb(main):016:0> b
=> 2
irb(main):018:0> a,b = [1,2,3]
=> [1, 2, 3]
irb(main):019:0> a
=> 1
irb(main):020:0> b

The || operator is similar to the null coalescing operator, ??, in C#. If a variable is not currently set (i.e. is nil), then set it to the specified value:

irb(main):021:0> v = nil
=> nil
irb(main):022:0> v = v || "hello"
=> "hello"
irb(main):023:0> v
=> "hello"
irb(main):024:0> v = "bye!"
=> "bye!"
irb(main):025:0> v ||= "hello"
=> "bye!"
irb(main):026:0> v
=> "bye!"

Symbols

Symbols are peculiar to Ruby. In essence they are a declare-once object, which then only has a single instance no matter where it is used in a Ruby session. They are declared as follows, by prefixing an unquoted string (or quoted string with spaces), by a colon “:” :

irb(main):046:0> :foo
=> :foo
irb(main):047:0> :"hello there"
=> :"hello there"

And can be returned as strings:

irb(main):048:0> :"hello there".to_s
=> "hello there"
irb(main):049:0> :foo.to_s
=> "foo"

But cannot be assigned to once they are declared:

irb(main):054:0> :foo = :"hello there"
SyntaxError: (irb):54: syntax error, unexpected '=', expecting $end
:foo = :"hello there"
      ^
        from C:/RailsInstaller/Ruby1.9.2/bin/irb:12:in `<main>'

Footnote to this section, in Ruby versions prior to 1.9.2, you were able to call the to_i method on a Symbol, but this is no longer valid (e.g. see here).

We can see the global symbol table, by calling Symbol.all_symbols, or just get a subset:

irb(main):078:0> Symbol.all_symbols.size
=> 3528
irb(main):079:0> Symbol.all_symbols[1,20]
=> [:"<IFUNC>", :"<CFUNC>", :respond_to?, :"core#set_method_alias", :"core#set_v
ariable_alias", :"core#undef_method", :"core#define_method", :"core#define_singl
eton_method", :"core#set_postexe", :each, :length, :size, :lambda, :intern, :get
s, :succ, :method_missing, :send, :__send__, :initialize]

Arrays and Method Naming Convention

Returning to the Array class. Consider:

irb(main):111:0> a = [1,2,[3,4, [5,6]]]
=> [1, 2, [3, 4, [5, 6]]]
irb(main):112:0> a.flatten
=> [1, 2, 3, 4, 5, 6]
irb(main):113:0> a
=> [1, 2, [3, 4, [5, 6]]]

Notice that a is unchanged. Now try:

irb(main):114:0> a.flatten!
=> [1, 2, 3, 4, 5, 6]
irb(main):115:0> a
=> [1, 2, 3, 4, 5, 6]

In general, methods that end in ! indicate that the method will modify the object it’s called on.

i.e. objects are modified in place: see this question on Stackoverflow.

Hashes

Ruby hashes, if you are familiar with Python and Perl, are very similar:

A Hash is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. Hashes enumerate their values in the order that the corresponding keys were inserted.

Hashes have a default value that is returned when accessing keys that do not exist in the hash. By default, that value is nil.

We can declare hashes (where keys can be anything, but we’re using Symbols):

irb(main):073:0> h = {}
=> {}
irb(main):074:0> h = { :foo => "hello" }
=> {:foo=>"hello"}
irb(main):075:0> h = { :foo => "hello", :bar => "there" }
=> {:foo=>"hello", :bar=>"there"}

Appending or changing existing key/value pairs:

irb(main):080:0> h[:boo] = "hello"
=> "hello"
irb(main):081:0> h[:foo] = "goodbye"
=> "goodbye"
irb(main):082:0> h
=> {:foo=>"goodbye", :bar=>"there", :boo=>"hello"}

Simple iteration through the keys in the hash:

irb(main):084:0> h.each_key {|key| puts key }
foo
bar
boo
=> {:foo=>"goodbye", :bar=>"there", :boo=>"hello"}#

and through the values;

irb(main):085:0> h.each_value {|value| puts value }
goodbye
there
hello
=> {:foo=>"goodbye", :bar=>"there", :boo=>"hello"}

See the documentation page here for all the hash functions, e.g.

irb(main):097:0> h = {}
=> {}
irb(main):098:0> h.class
=> Hash
irb(main):099:0> Hash.instance_methods
=> [:rehash, :to_hash, :to_a, :inspect, :to_s, :==, :[], :hash, :eql?, :fetch........

Introducing The Splat Operator *

The splat operator*” does a few things. First if we define a simple function:

irb(main):027:0> def foo * args
irb(main):028:1>  args
irb(main):029:1> end
=> nil

And then call it:

irb(main):030:0> foo 1
=> [1]
irb(main):031:0> foo(1)
=> [1]
irb(main):032:0> foo(1, "hello", "world")
=> [1, "hello", "world"]

It means that we can call the method foo with varargs (or params if you’re a C# person).

Consider the multiple assignment;

irb(main):033:0> x,y = 1,2,3
=> [1, 2, 3]
irb(main):034:0> x
=> 1
irb(main):035:0> y
=> 2

Adding the splat operator to y, makes the assignment ‘greedy’:

irb(main):036:0> x, *y = 1,2,3
=> [1, 2, 3]

And we then have:

irb(main):037:0> x
=> 1
irb(main):038:0> y
=> [2, 3]

where y now contains the remaining values in the right-hand-side array.

Interesting Links:

A Ruby Crash Course: Day 1

As a challenge and to broaden my knowledge, I thought I’d spend a few days looking at Ruby. Like any programming language, you aren’t going to learn it in a week, but I can at least familiarise myself with the syntax, and perform some common tasks. I am going to be using Windows 7 as my desktop enviornment.

Learning a new language is always useful as it introduces you to concepts that aren’t perhaps implemented in languages that you are already familiar with (e.g. see the great generators pdf slideshow by Dave Beazley).

I hear and I forget; I see and I remember; I do and I understand.

tl;dr

Straightforward syntax and easy to pick up the basics.

Getting Ruby

I have chosen to get the full Rails installer in case, by the end of the week, I need to do something with Rails. This installs, Ruby, Rails, Git, and a few other things.

Books and Online Documenation

One free online book is referred to as the Pickaxe: Programming Ruby: The Pragmatic Programmers’ Guide.

And the official documentation is here.

Terminology

Where possible I will try and use Ruby terminology, however since I’m starting this from a C++ and Python background I may make some mistakes.

Day 1 – The Quick Start Guide

Now to run through the Ruby Quickstart. What follows is a trawl through the example, plus some of my notes along side it.

Hello World

First principles. Fire up the interactive Ruby console from the Start Menu, and:

irb(main):001:0> puts "hello world"
hello world
=> nil
irb(main):002:0>

But it is case sensitive:

irb(main):004:0> math.sqrt(9)
NameError: undefined local variable or method `math' for main:Object
        from (irb):4
        from C:/RailsInstaller/Ruby1.9.2/bin/irb:12:in `<main>'
irb(main):005:0> Math.sqrt(9)
=> 3.0
irb(main):006:0>

Lists

We can just define a list as so:

irb(main):001:0> a = ['hello', 'there']
=> ["hello", "there"]

or

irb(main):003:0> a = ["hello", "there"]
=> ["hello", "there"]

We return to these later.

First function

The definition is quite straightforward:

irb(main):014:0> def hello
irb(main):015:1> puts "hello world!"
irb(main):016:1> end
=> nil
irb(main):017:0> hello
hello world!
=> nil
irb(main):018:0> hello()
hello world!
=> nil

Note that parameterless functions can be optionally called with or without parentheses.

A Second Function

Not in the quick start, and a digression of my own to figure out the calling syntax. Consider a 2 parameter function:

irb(main):060:0> def foo(a,b)
irb(main):061:1> puts " #{a} --> #{b}"
irb(main):062:1> end
=> nil

Valid:

irb(main):063:0> foo "x", "y"
 x --> y
=> nil

irb(main):068:0> foo("x","y")
 x --> y
=> nil

Invalid:

irb(main):064:0> foo "x" "y"
ArgumentError: wrong number of arguments (1 for 2)

irb(main):065:0> foo ("x","y")
SyntaxError: (irb):65: syntax error, unexpected ',', expecting ')'

The puts "#{var_name}" is similar to string formatting syntax in other languages.

First class

Ruby doesn’t respect indentation like python (though idented for clarity here):

irb(main):025:0> class Greeter
irb(main):026:1>  def initialize(name = "world")
irb(main):027:2>   @name = name
irb(main):028:2>  end
irb(main):029:1>  def say_hi
irb(main):030:2>   puts "Hi #{@name}!"
irb(main):031:2>  end
irb(main):032:1>  def say_bye
irb(main):033:2>   puts "Bye #{@name}"
irb(main):034:2>  end
irb(main):035:1> end

Insantiating the object:

irb(main):036:0> g = Greeter
=> Greeter
irb(main):037:0> g.say_hi
NoMethodError: undefined method `say_hi' for Greeter:Class
        from (irb):37
        from C:/RailsInstaller/Ruby1.9.2/bin/irb:12:in `<main>'

We are not creating a new object so it fails. We need to do this, which constructs the class with the default parameter:

irb(main):038:0> g = Greeter.new
=> #<Greeter:0x47eab8 @name="world">
irb(main):040:0> g.say_hi
Hi world!
=> nil

or

irb(main):041:0> g = Greeter.new("Mike")
=> #<Greeter:0x283ec60 @name="Mike">
irb(main):042:0> g.say_hi
Hi Mike!
=> nil
irb(main):043:0>

with a parameter. Parentheses are still optional on the say_hi method.

Inspecting the class

All methods on the class, including those that are inherited:

irb(main):050:0> Greeter.instance_methods()
=> [:say_hi, :say_bye, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singl
eton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?,
 :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :inspect, :m
ethods, :singleton_methods, :protected_methods, :private_methods, :public_method
s, :instance_variables, :instance_variable_get, :instance_variable_set, :instanc
e_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send
, :respond_to?, :respond_to_missing?, :extend, :display, :method, :public_method
, :define_singleton_method, :__id__, :o bject_id, :to_enum, :enum_for, :==, :equa
l?, :!, :!=, :instance_eval, :instance_exec, :__send__]

And just the methods that we have defined:

irb(main):051:0> Greeter.instance_methods(false)
=> [:say_hi, :say_bye]

Available class methods

Using respond_to?:

irb(main):052:0> g.respond_to?('say_hi')
=> true
irb(main):053:0> g.respond_to?('to_s')
=> true

There are a couple of things going on here:

  • The ? in Ruby is actually part of the method name, unlike in C++ where it is the ternary operator or trigraph.
  • The method to_s is a built-in method on the class.

However for

irb(main):055:0>  g.respond_to?('name')
=> false

Revisiting lists:

Note that if we return to our list:

irb(main):003:0> a = ["hello", "there"]
=> ["hello", "there"]

The instance_methods call on a list is not supported. However respond_to? is:

irb(main):008:0> a.respond_to?("each")
=> true
irb(main):009:0> a.respond_to?("join")
=> true

Iterating over the list

Since the list supports each, how do we use it? Quite straightfoward, call each, which it responds to, on the list:

irb(main):013:0> a.each do |item|
irb(main):014:1* puts item
irb(main):015:1> end
hello
there
=> ["hello", "there"]

Extending a Class

We can extend an already defined class. Firstly try this:

irb(main):069:0> class Greeter
irb(main):070:1>   attr_accessor : name
irb(main):071:1> end
SyntaxError: (irb):70: syntax error, unexpected ':', expecting keyword_end
  attr_accessor : name
                 ^
        from C:/RailsInstaller/Ruby1.9.2/bin/irb:12:in `<main>'

which doesn’t work. Now try this:

irb(main):072:0> class Greeter
irb(main):073:1>   attr_accessor :name
irb(main):074:1> end
=> nil

The colon (:) syntax for the member-variable name is important. We have now defined two new methods:

irb(main):075:0> g.respond_to?("name")
=> true
irb(main):076:0> g.respond_to?("name=")
=> true

Note that we can define set name with a space between name and =:

irb(main):077:0> g.name = "Fred"
=> "Fred"
irb(main):078:0> g.say_hi
Hi Fred!
=> nil

Annoyingly though, I though I would google for attr_accessor and see what immediately turns up, and none of the results were a direct definition. However this link has an explanation and nice comparison of long hand versus short hand:

class Dog

  def initialize(a_name)
    @name = a_name
  end

  def name  #get the name
    return @name
  end

  def name=(a_name) #set the name
    @name = a_name
  end

end

d = Dog.new("Spot")
puts d.name   #Spot

d.name = "Red"
puts d.name   #Red

Compare to:

class Dog
  attr_accessor :name

  def initialize(a_name)
    @name = a_name
  end

end

d = Dog.new("Spot")
puts d.name   #Spot

d.name = "Red"
puts d.name  #Red

The Final Quick Start Example.

The final example in the quick start guide is the Greeter class extended to take a name, or list of names.

class MegaGreeter
  attr_accessor :names

  # Create the object
  def initialize(names = "World")
    @names = names
  end

  # Say hi to everybody
  def say_hi
    if @names.nil?
      puts "..."
    elsif @names.respond_to?("each")

      # @names is a list of some kind, iterate!
      @names.each do |name|
        puts "Hello #{name}!"
      end
    else
      puts "Hello #{@names}!"
    end
  end

  # Say bye to everybody
  def say_bye
    if @names.nil?
      puts "..."
    elsif @names.respond_to?("join")
      # Join the list elements with commas
      puts "Goodbye #{@names.join(", ")}.  Come back soon!"
    else
      puts "Goodbye #{@names}.  Come back soon!"
    end
  end

end

if __FILE__ == $0
  mg = MegaGreeter.new
  mg.say_hi
  mg.say_bye

  # Change name to be "Zeke"
  mg.names = "Zeke"
  mg.say_hi
  mg.say_bye

  # Change the name to an array of names
  mg.names = ["Albert", "Brenda", "Charles",
    "Dave", "Englebert"]
  mg.say_hi
  mg.say_bye

  # Change to nil
  mg.names = nil
  mg.say_hi
  mg.say_bye
end

Note that we switch on the attribute based on whether it supports each and join. The output is as follows;

C:\Temp>ruby test.rb
Hello World!
Goodbye World.  Come back soon!
Hello Zeke!
Goodbye Zeke.  Come back soon!
Hello Albert!
Hello Brenda!
Hello Charles!
Hello Dave!
Hello Englebert!
Goodbye Albert, Brenda, Charles, Dave, Englebert.  Come back soon!
...
...

C:\Temp>

Having written code similar to this in python (and using isinstance), this is quite obvious.

Null, or nil!

A null, or rather nil variable can be defined and tested as follows:

irb(main):017:0> x = nil
=> nil
irb(main):018:0> x.nil?
=> true

irb(main):019:0> x = ''
=> ""
irb(main):020:0> x.nil?
=> false

Duck Typing

Quoting from the quick start:

The say_bye method doesn’t use each, instead it checks to see if @names responds to the join method, and if so, uses it. Otherwise, it just prints out the variable as a string. This method of not caring about the actual type of a variable, just relying on what methods it supports is known as ‘Duck Typing’, as in ‘if it walks like a duck and quacks like a duck’. The benefit of this is that it doesn’t unnecessarily restrict the types of variables that are supported. If someone comes up with a new kind of list class, as long as it implements the join method with the same semantics as other lists, everything will work as planned.

Again, this is not dissimilar to Python.

int main

Ruby uses this trick:

if __FILE__ == $0
   #  code here....
end

to run your main, where as Python has this:

if __name__ == "__main__":
    main()

and C/C++ typically just have:

int main(int argc, char **argv)
{ .... code .... }

(depending on your compiler, defined entry points and what-not).

Conclusion for Day 1

The feeling so far is that Ruby is not dissimilar to python at novice usage levels, however the syntax has a few inconsistencies (not dissimilar to perl, and those that the Python 3 release tries to resolve in Python 2).

C+11 Part 3: rvalue References

In C++11 rvalue references and move semantics have the ability to improve the efficiency and performance of your code in terms of speed and memory usage, but what actually happens when you use them?

If you need to familiarise yourself with rvalue references, I suggest that you read this page first: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2027.html.

We will just create a simple Widget and Foo classes and stub out all the default constructors, then add some ref-ref parameters, move constructors, and good old fashioned cout statements:

#include <iostream>
#include <vector>
#include <utility>

using namespace std;

struct Foo
{
    int m;
    int * p;

    Foo() : m(0), p(new int(m))
      { cout << "-- Foo()" << endl; }

    Foo(int i) : m(i), p(new int(m))
      { cout << "-- Foo(int i)" << endl; }

    //  copy POD types, and re-assign pointers.
    Foo(Foo && other) : m(other.m), p(other.p) {
        other.p = nullptr;
        other.m = -1;
        cout << "-- Foo(Foo && other)" << endl;
    }

    //  standard copy constructor
    Foo(Foo const & other) : m(other.m), p(new int(*other.p))
      { cout << "-- Foo(Foo & other)" << endl; }

    ~Foo() {
      delete p;
      cout << "-- ~Foo() : " << m  << endl;
    }
};

struct Widget
{
    Foo m_foo;

    Widget(void)  { cout << "-- Widget()" << endl; }

    Widget(Foo const & foo) : m_foo(foo)
      { cout << "-- Widget(Foo const & foo)" << endl; }

    Widget(Foo && foo) : m_foo(std::move(foo))
      { cout << "-- Widget(Foo && foo)" << endl; }

    ~Widget(void)
      { cout << "-- ~Widget(void) : " << m_foo.m << endl; }

    Widget(Widget && other) : m_foo(std::move(other.m_foo))
      { cout << "-- Widget(Widget && other)" << endl; }

    Widget(Widget const && other) : m_foo(std::move(other.m_foo))
      { cout << "-- Widget(Widget const && other)" << endl; }

    Widget(Widget const & other) :  m_foo(other.m_foo)
      { cout << "-- Widget(Widget const & other)" << endl; }
};

void main()
{
    {
        cout << endl << endl << "Foo f(1); // non temp Foo;" << endl;
        cout << "Widget w(f);" << endl;
        Foo f(1);  // non temp Foo
        Widget w(f);
    }

    {
        cout << endl << endl << "Widget w2(Foo(2));  // temp Foo" << endl;
        Widget w2(Foo(2));  // temp Foo
    }

    {
        cout << endl << endl << "v.push_back(Widget(Foo(3)));" << endl;
        vector<Widget> v;
        v.push_back(Widget(Foo(3)));
    }
}

Taking the Foo class first (elided):

struct Foo
{
    int m;
    int * p;

    Foo(Foo && other) : m(other.m), p(other.p)  { other.p = nullptr; other.m = -1; }
};

It has two members, an int and a pointer to some memory (in this case just an int), and the move constructor. Since we’re dealing with POD types, we simply copy these: as we know this constructor is only called in the context of a move we can take ownership of the pointer, and set it to null in other which will be going out of scope shortly. I’m setting m to -1 purely to make it stand out in the output that follows.

The Widget class has a Foo member (elided):

struct Widget
{
    Foo m_foo;

    Widget(Foo && foo) : m_foo(std::move(foo)) {}

    Widget(Widget const & other) :  m_foo(other.m_foo) {}

    Widget(Widget && other) : m_foo(std::move(other.m_foo)) {}

    Widget(Widget const && other) : m_foo(std::move(other.m_foo)) {}
};

Why are we using std::move here?

std::move obtains an rvalue reference to its argument.

It is typically used to implement move semantics when invoking functions. When std::move is used the compiler will look for a function overload that takes an rvalue reference. This means that the contents of t will be moved into the function, leaving t as an xvalue.

If we were to write:

Widget(Widget && other) : m_foo(other.m_foo) {}

the constructor called is inferred by the type of other.m_foo and would just call Foo‘s copy constructor. So to ensure that the move constructor of Foo is called, we call std::move.

You need to call std::move to ensure the move constructor is called on complex types.

Note that there are two move constructors here, a const and non-const version: this is explained a little later (tl;dr: you only need to define one of them).

The Output

If we run the code (under Visual Studio 11 Beta), the textual output is as follows:

Foo f(1); // non temp Foo;
Widget w(f);
-- Foo(int i)
-- Foo(Foo & other)
-- Widget(Foo const & foo)
-- ~Widget(void) : 1
-- ~Foo() : 1
-- ~Foo() : 1

Widget w2(Foo(2));  // temp Foo
-- Foo(int i)
-- Foo(Foo && other)
-- Widget(Foo && foo)
-- ~Foo() : -1
-- ~Widget(void) : 2
-- ~Foo() : 2

v.push_back(Widget(Foo(3)));
-- Foo(int i)
-- Foo(Foo && other)
-- Widget(Foo && foo)
-- Foo(Foo && other)
-- Widget(Widget && other)
-- ~Widget(void) : -1
-- ~Foo() : -1
-- ~Foo() : -1
-- ~Widget(void) : 3
-- ~Foo() : 3

Explaining what is going on here is fairly straightforward. Taking the first part of the output:

Foo f(1); // non temp Foo;
Widget w(f);
-- Foo(int i)
-- Foo(Foo & other)
-- Widget(Foo const & foo)
-- ~Widget(void) : 1
-- ~Foo() : 1
-- ~Foo() : 1

We create a local object on the stack, and the Widget class’s constructor that takes a const-ref object is called. This is the usual behaviour. A temporary object is created, the temporary is copied into Widget‘s member variable, and the temporary is then destroyed, and the stack is unwound.

The second part of the output:

Widget w2(Foo(2));  // temp Foo
-- Foo(int i)
-- Foo(Foo && other)
-- Widget(Foo && foo)
-- ~Foo() : -1
-- ~Widget(void) : 2
-- ~Foo() : 2

What actually happens is:

  • Construct a Widget

    • Compiler knows construction is occurring with a temporary, so calls move constructor.
    • Create a temporary Foo(2)
    • Call the Foo move constructor to assign contents of temporary to Widget‘s Foo member. Note the ‘-1′ value which is set on the temporary by the move constructor after it takes ownership of the temporary’s members.
    • Call temporary Foo‘s destructor
  • Call Widget‘s destructor

    • Call member Foo‘s destructor

The last piece of output is (with annotation showing where each line of output comes from):

v.push_back(Widget(Foo(3))); (vector(temp widget(temp foo))
-- Foo(int i)                (temp foo:  Foo(3) construction)
-- Foo(Foo && other)         (temp widget:  m_foo construction)
-- Widget(Foo && foo)        (temp widget:  construction)
-- Foo(Foo && other)         (vector widget: m_foo construction)
-- Widget(Widget && other)   (vector widget: construction)
-- ~Widget(void) : -1        (temp widget destructor)
-- ~Foo() : -1               (temp widget destructor)
-- ~Foo() : -1               (temp foo destructor)
-- ~Widget(void) : 3         (vector widget destructor)
-- ~Foo() : 3                (vector widget: m_foo destructor)

Note that as this is text output, it’s not the same as the call stack ordering.

In this example we are just adding a Widget into a vector. As we can see above, push_back is now implemented in terms of rvalue references. As we insert a Widget into a vector we get a second Widget being created, and hence a third Foo.

Const and non-const rvalue references

This link http://cpp-next.com/archive/2009/09/move-it-with-rvalue-references/ has a helpful lookup table for the resolution of rvalue references and regular references:

The C++11 rules for reference binding and overload resolution are summarized in the table below, :

Expression→
Reference Type↓
T
rvalue
const T
rvalue
T
lvalue
const T
lvalue
Priority
T&& X 4
const T&& X X 3
T& X 2
const T& X X X X 1

The “Priority” column describes how these references behave with respect to overload resolution. For example, given the following overload set:

void f(int&&);        // #1
void f(const int&&);  // #2
void f(const int&);   // #3

passing an rvalue of type const int to f will invoke overload #2, because overload #1 represents a disallowed binding and #3 appears in a row with lower priority.

So generally, we only need to define the non const rvalue reference type, i.e.

void foo(T && t);

Assorted References

  1. http://msdn.microsoft.com/en-us/library/dd293665.aspx/
  2. http://msdn.microsoft.com/en-us/library/dd293668.aspx/
  3. http://en.cppreference.com/w/cpp/utility/move/
  4. http://cpp-next.com/archive/2009/09/move-it-with-rvalue-references/
  5. http://en.cppreference.com/w/cpp/container/vector/emplace_back/
  6. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2027.html#Move_Semantics/