Does to!(string)(char[]) do any memory allocation on conversion?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Dec 27 10:20:12 UTC 2017


On Monday, December 25, 2017 15:00:19 aliak via Digitalmars-d-learn wrote:
> On Monday, 25 December 2017 at 14:12:32 UTC, Marc wrote:
> > Does to!(string)(char[]) do any memory allocation on conversion
> > or is this similar to a cast or what else?
>
> As said it calls idup, which calls _trustedDup which seems to
> call _dup which does memory allocation ->
> https://github.com/dlang/druntime/blob/v2.077.1/src/object.d#L3863
>
> I think you can use assumeUnique to avoid allocs though. See code
> gen here:
>
> https://godbolt.org/g/44pLpL

assumeUnique just casts to immutable and should be used with extreme care as
casting from mutable or const to immutable runs a serious risk of subtle
bugs if done incorrectly. If you do it, the reference being cast really
needs to be the only reference to that object.

Almost always, the better approach is to construct an object with a pure
function that is able to implicitly convert its return value to immutable,
because the compiler is able to prove that the mutable object was not passed
into the function and therefore that it is unique.

In the case of strings, to!string is good to use, but it will result in a
new string being allocated if it's not given an immutable string.
std.conv.to generally tries to ensure that conversions are done in a safe
manner, and casting mutability is risky business and best to be avoided in
general.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list