initialization of structs
Christian Köstlin
christian.koestlin at gmail.com
Tue Sep 27 14:27:19 PDT 2011
On 09/26/2011 11:15 PM, Timon Gehr wrote:
> On 09/26/2011 10:55 PM, Christian Köstlin wrote:
>> Hi,
>>
>> I have the problem, that I want to always construct a struct with a
>> parameter. To make this more comfortable (e.g. provide a default
>> parameter I have a factory function to create this struct).
>>
>> struct S {
>> int i;
>> this(int i_) { i = i_; }
>> }
>>
>> S createS(int i=5) {
>> return S(i);
>> }
>>
>> My question now is:
>> Is there a way to enfore the creation of the struct with createS?
>> Or to put it in another way. Is it possible to forbid something like:
>> S s; or even auto s = S(1);? I read about the this(this) thing, but that
>> is only used when the struct is copied, as far as I understood.
>>
>>
>> (My struct has the nature to only work if it is not constructed with the
>> default struct constructor).
>>
>> thank in advance
>>
>> christian
>
> Starting with DMD 2.055, this works.
>
> struct S{
> this() @disable;
> this(int i_) { i = i_; }
> }
mhh ... strange ... i have dmd 2.055 64bit for linux and this compiles
without error and outputs
l: 0
c: 0
import std.stdio : writeln;
struct S {
private:
int[] data;
@disable this(this);
@disable this();
this(size_t s) {
data = new int[s];
}
public:
void p() {
writeln("l: ", data.length);
writeln("c: ", data.capacity);
}
static S create(size_t s = 8) {
return S(s);
}
}
unittest {
auto s = S();
s.p();
}
int main(string[] args) {
return 0;
}
shouldnt this lead to a compile error?
thanks in advance
christian
More information about the Digitalmars-d-learn
mailing list