On Sunday, 30 June 2013 at 02:20:24 UTC, Diggory wrote:
On Saturday, 29 June 2013 at 17:57:33 UTC, TommiT wrote:
On Saturday, 29 June 2013 at 13:47:36 UTC, TommiT wrote:
[..]
Example:
----
struct S
{
int[] values;
this(this)
{
values = values.dup;
}
}
void foo(const S) { }
void main()
{
const S s;
foo(s); // No need to call postblit
}
One important related detail:
If the compiler decides to elide the postblit of S on the call
to foo(s), then the destructor of S (if S happened to have
one) should not be called when the call to foo exits and the
argument passed to foo goes out of scope. The logic behind
this is that when we omit the postblit on the argument that's
passed by value, it is as-if we had passed the argument by
const reference (except that the argument is considered local
to foo, i.e. not returnable by reference and what not).
Unless the function is pure, this is only possible for
immutable parameters otherwise the original variable may be
modified while inside the function even if it is passed by
const.
I'm not sure I follow. Are you saying...
1) the function foo could cast away const and modify s
or
2) some other thread could modify s while foo is executing
case 1:
void foo(const S s)
{
S m = cast(S) s;
s.values[0] = 42;
}
I'm not sure how this is in D, but I think in C++, casting away
const and then modifying the variable is potentially undefined
behaviour. I think the compiler should be free to assume that the
programmer hasn't written code that has undefined behaviour.
case 2:
I don't think another thread could be modifying s, because it's
not shared, i.e. it's a thread local variable. If the parameter
to foo was "shared const S", then it could be modified by another
thread, and thus the postblit could not be elided.