digitalmars.D.learn - DLang BetterC dynamic arrays
- dtoadq (33/33) Dec 24 2018 One of the major things holding me back from using BetterC is
- dtoadq (12/12) Dec 24 2018 Ah, of course I find the solution immediately after I post. At
- Steven Schveighoffer (6/19) Dec 24 2018 Careful there, data[0 .. size] is for size elements of T.sizeof, not
One of the major things holding me back from using BetterC is https://issues.dlang.org/show_bug.cgi?id=18949 . Until this is fixed (if it ever is), we are stuck with implementing our own arrays. The problem comes that the default constructor of a struct must be default or disabled, which means syntax must always be like this: auto myArr = Array!int(0); Preferably I would disable default constructor, so arrays can not ever be in a null state. Unfortunately, this is impossible, because if I wanted to make `myArr` a member of a struct, it would have to default to a null initialization state so I can then properly allocate it in all constructors. In other words, struct Foo { auto myArr = Array!int(0); } Generates an error "malloc cannot be interpreted at compile time". It must be written as: struct Foo { Array!int myArr; this ( int i ) { myArr = Array!int(0); } } This is catastrophic because now everything has to start in a null-state, if any one of its members (or their members, etc) has an array. For example, I can't even do this now: struct Bar { auto foo = Foo(0); } I have to always include an arbitrary constructor with an arbitrary parameter just so I can initialize my arrays to their proper default state. Is there any fix? The two BetterC libraries I saw with arrays all suffer from this problem AFAIK.
Dec 24 2018
Ah, of course I find the solution immediately after I post. At least it seems to work fine; ``` struct Array(T) { T[] foo; this ( size_t size ) { T* data = cast(T*)malloc(size); foo = data[0..size]; } } ``` :-)
Dec 24 2018
On 12/24/18 5:07 PM, dtoadq wrote:Ah, of course I find the solution immediately after I post. At least it seems to work fine; ``` struct Array(T) { T[] foo; this ( size_t size ) { T* data = cast(T*)malloc(size); foo = data[0..size]; } } ```Careful there, data[0 .. size] is for size elements of T.sizeof, not bytes (which is what you passed into malloc). Better: T* data = cast(T*)malloc(size * T.sizeof); -Steve
Dec 24 2018