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.
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?
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#.
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With