DIP 1016 and const ref parameters

XavierAP n3minis-git at yahoo.es
Wed Jun 19 18:28:12 UTC 2019


On Wednesday, 19 June 2019 at 12:55:09 UTC, Jonathan M Davis 
wrote:
>
> Even in C++, using const ref is not as good a practice as it 
> once was, because they added move constructors, finally making 
> object moveable. The result is that in many cases, it's 
> actually more efficient to just copy values in C++ rather than 
> use const &, but which is better does depend on the code.
>
> As for D, unless you're dealing with large objects, odds are 
> that worrying about passing by value is pointless. D classes 
> are reference types, and D structs have move semantics 
> built-in. So, you don't get as many copies as you would in 
> C++98, and the situation is probably better than newer versions 
> of C++, since IIRC, C++ classes aren't moveable by default, 
> whereas D structs are. In general, you're probably better off 
> just passing by value unless you find that a particular piece 
> of code is inefficient when benchmarking. Either way, you don't 
> want to be slapping const on everything the way you would in 
> C++, because D's const is far more restrictive. So, while it 
> still can be quite useful, odds are that if you start using it 
> heavily, you're going to run into problems fast - especially 
> since casting away const and mutating an object is undefined 
> behavior in D. D's const has no back doors. If something is 
> const, then you can't mutate it unless you also have a mutable 
> reference to the same data. And because const is transitive, 
> you pretty much can't get mutable stuff from const stuff like 
> you frequently can in C++ (e.g. in C++, it's possible to have a 
> const container of mutable objects, wherein D, once part of 
> something is const, everything within that part is const).
>
> As for the DIP, I'd suggest watching Andrei's recent dconf talk 
> on the subject:
>
> https://www.youtube.com/watch?v=aRvu2JGGn6E&feature=youtu.be
>
> - Jonathan M Davis

I am not talking about cases that would be candidate for moving, 
or where const would be any problem. If you want an example for 
the sake of argument:

struct Matrix3D
{
Matrix3D opBinary(string op)(const ref Matrix3D rhs) const;
}
unittest
{
	auto a = Matrix3D.random;
	assert(a == a * Matrix3D.identity);
	assert(a == a + Matrix3D.zeros);
}

I did watch Andrei's talk, actually this is where I started and 
learned about the DIP(s), then I was confused that 1016 had been 
rejected, and smelling that it may be "reopening" I was not sure 
where I can find the "index" of DIPs under discussion or 
whatever... :)

> IIRC, C++ classes aren't moveable by default, whereas D structs 
> are.

What do you mean that structs are movable? I know about RVO (in 
both D and C++, supposedly guaranteed by all compilers in 
practice, but not by language spec -- why not D?), but what about 
passing up the stack as here?


More information about the Digitalmars-d-learn mailing list