DMD supports Named Return Value Optimization(NRVO), but now this
doesn't work for struct that has @disabled postblit and user-defined
destructor (e.g. std.typecons.scoped).
This looks trivial, but serious problem.
1. Need of incorporating NRVO into the language specifications
D does not contain rvalue seantinc in its type system.
('ref' is storage class, not part of type. This means casting
is useless for this purpose, unlike C++.)
Except for only one, This means D has no way that convert from lvalue
to rvalue in current language spec.
The one way is NRVO. This is not only trivial optimization, but also
core of move semantics in D.
----
T f(){
T ret; // &ret == hidden pointer, and *hidden is 'move target'.
// In this example, share memory of t.
ret = ...
return ret; // NRVO.
}
T t = f(); // t's memory address is taken hidden pointer
----
Moving object caller to callee is now D supports, but reversed flow is
limitation. To full support moving callee to caller through return value,
NRVO is required.
2. std.algorithm.move problem
If Issue 4499 will be fixed, unary std.algorithm.move() will not work
on noncopyable/has expplicit destructor object.
To give correct behavior, NRVO spec update is need.
3. ABI problem
In http://digitalmars.com/d/2.0/abi.html 'Return Value' term,
struct its size is less than 8 byte is returned using registers.
Issue 4500 is scoped!T and self-referenced class problem, but the way
resolving it will need true NRVO. That has following spec: Any size object
returned through hidden pointer,
if the object has elaborate destructor at least.
See http://d.puremagic.com/issues/show_bug.cgi?id=4500#c5 . Attachment code
includes workaround for this issue, But it's too ugly.
Do you think?
Comment #1 by k.hara.pg — 2011-03-25T19:06:29Z
Related issues:
On return statement, copy construction should work correctly.
- Issue 4437 - copy construction bug with "return this;"
- Issue 4499 - calls to @disabled postblit are emitted
Struct literal/constructor call should be rvalue.
- Issue 5178 - StructLiteral should not be lvalue
- Issue 5769 - struct elaborate constructor should make rvalue
Comment #2 by k.hara.pg — 2011-03-25T19:27:32Z
Created attachment 935
3 Patches
These patches has 3 points.
1. Allow NRVO for user-defined destructor object.
2. Eliminate destructor call of return value that non-copyable object in NRVO function.
3. On assignment (e1 = e2) if e2 is non-copyable and prvalue, this expression generates following code:
e1.__dtor();
e1 = e2; // bit copy
This is much experimental, but I hope that it helps the language evolution.
Comment #3 by k.hara.pg — 2011-04-13T10:38:46Z
On trunk dmd, this code cannot compile because of fixing bug4499.
----
import std.algorithm;
struct S
{
@disable this(this){}
~this(){}
}
void main()
{
S s1;
S s2 = move(s1);
}
----
Comment #4 by k.hara.pg — 2011-05-05T06:15:51Z
Created attachment 963
2 patches
Update patches.
Changes:
Behavior changes on assignment (Comment#3 3.) makes bug, so I remove it.