Reputation: 5805
I am a novice in D programming language. I am going to write some bindings of a C library in D. So this question.
Suppose we have a struct S
(not class!)
Suppose all of the following are expensive operations:
S
initialization (constructor);S
finalization (destructor);S
postblit.Now I want to pass S
values around like this:
S func(const ref S x) {
return S(x);
}
Question: Will excessive (more than minimally enough to express my algorithm) use of the above expensive operations happen? If yes, how to prevent this?
Note that I use struct rather than class from practical performance reasons.
Upvotes: 0
Views: 57
Reputation: 5805
The following program shows that excessive copying does happen:
$ ./init_test
Initialization
Postblit
Finalization
Finalization
Program text:
import std.stdio;
struct Expensive {
static create() {
writeln("Initialization");
return Expensive.init;
}
~this() {
writeln("Finalization");
}
this(this) {
writeln("Postblit");
}
}
Expensive func(const Expensive x) { // `ref const` results in compilation error
return x;
}
void main() {
Expensive obj = func(Expensive.create());
}
Upvotes: 0