On Monday, December 21, 2015 05:43:59 Jakob Ovrum via Digitalmars-d-learn wrote: > On Monday, 21 December 2015 at 05:41:31 UTC, Shriramana Sharma > wrote: > > Rikki Cattermole wrote: > > > >> string myCString = cast(string)ptr[0 .. strLen]; > > > > Thanks but does this require that one doesn't attempt to append > > to the returned string using ~= or such? In which case it is > > not safe, right? > > Growing operations like ~= will copy the array to a GC-allocated, > druntime-managed array if it isn't one already.
Exactly. As long as the GC has not been disabled, that there is sufficient memory to allocate, and that appending elements does not result in an exception being thrown (which it wouldn't with arrays of char) ~= should always work. When ~= is used, the runtime looks at the capacity of the dynamic array to see whether it has enough room to grow to fit the new elements. If it does, then the array is grown into that space. If it doesn't, then a block of GC memory is allocated, the elements are copied into that memory, and the dynamic array is set to point to that block of memory. Whether the array is pointing to a GC-allocated block of memory or not when ~= is called is irrelevant. If it isn't, all that means is that the array's capacity will be 0, so it's going to have to reallocate, whereas if it were GC-allocated, it might have enough capacity to not need to reallocate. In either case, the operation will work. - Jonathan M Davis