xvalue and std::move in D
Ali Çehreli
acehreli at yahoo.com
Thu Mar 6 09:08:36 PST 2014
On 03/06/2014 03:21 AM, Edwin van Leeuwen wrote:
> Lately in C++ I have become a fan of the type of functional programming
> discussed here:
>
http://blog.knatten.org/2012/11/02/efficient-pure-functional-programming-in-c-using-move-semantics/
I haven't read that yet but I have always returned a vector from a
function that produced it instead of adding to a reference parameter.
> and was wondering if something similar is possible in D.
Most of the time it is automatic and a non-issue for arrays.
> Basically the idea is to define functions as follows:
>
> std::vector<double> add_to_vector( double x, std::vector<double> &&v ) {
> v.push_back(x);
> return v;
> }
Actually, when the name of the function is add_to_vector() anyway, there
is an obvious side-effect. So, I would not return the result in C++.
However, when the name is like make_vector() then I always return the
result. The alternatives have many hard questions to answer:
void make_vector(vector<double> & v)
{
// Should I clear v first?
// Should I simply start appending to v?
// etc.
}
All of the efficiency of doing that goes out the window when one
considers exception safety.
Anyway... Too much off topic... :)
> Is this possible in D?
T[] append(T)(T[] arr, T value)
{
arr ~= value;
return arr;
}
Done. :) Slices consist of two members that are cheap to copy: The
number of elements and the pointer to the first element. It is already
as efficient as move in C++.
You should also read the following article:
http://dlang.org/d-array-article.html
Ali
More information about the Digitalmars-d-learn
mailing list