Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Rvalue references and move semantics

Tags:

java

c++

c#

c++11

C++03 had the problem of unnecessary copies that could happen implicitly. For this purpose, C++11 introduced rvalue references and move semantics. Now my question is, do this unnecessary copying problem also exist in languages such as C# and java or was it only a C++ problem? In other words, does rvalue references make C++11 even more efficient as compared to C# or Java?

As far as C# concerned (operator overloading allowed in it), lets say we have a mathematical vector class, and we use it like this.

vector_a = vector_b + vector_c;

The compiler will surely transform vector_b + vector_c to some temporary object (lets call it vector_tmp).

Now I don't think C# can differentiate between a temporary rvalue such as vector_tmp or a an lvalue such as vector_b, so we'll have to copy data to vector_a anyway, which can easily be avoided by using rvalue references and move semantics in C++11.

like image 422
MetallicPriest Avatar asked Feb 29 '12 11:02

MetallicPriest


2 Answers

The problem comes up a lot. Someone I want to hold onto a unique copy of an object that no one else can modify. How do I do that?

  1. Make a deep copy of whatever object someone gives me? That would work, but it's not efficient.
  2. Ask people to give me a new object and not to keep a copy? That's faster if you're brave. Bugs can come from a completely unrelated piece of code modifying the object hours later.
  3. C++ style: Move all the items from the input to my own new object. If the caller accidentally tries to use the object again, he will immediately see the problem.
  4. Sometimes a C# read only collection can help. But in my experiences that's usually a pain at best.

Here's what I'm talking about:

class LongLivedObject
{
    private Dictionary <string, string> _settings;
    public LongLivedObject(Dictionary <string, string> settings)
    {   // In C# this always duplicates the data structure and takes O(n) time.
        // C++ will automatically try to decide if it could do a swap instead.
        // C++ always lets you explicitly say you want to do the swap.
        _settings = new Dictionary <string, string>(settings);
    }
}

This question is at the heart of Clojure and other functional languages!

In summary, yes, I often wish I had C++11 style data structures and operations in C#.

like image 143
Trade-Ideas Philip Avatar answered Oct 06 '22 10:10

Trade-Ideas Philip


yes unnecessary copy operation are there in C# and java.

does rvalue references make C++11 even more efficient as compared to C# or Java?

answer is yes. :)

like image 43
shofee Avatar answered Oct 06 '22 12:10

shofee