Why does toStringz return an immutable(char)*?
Jonathan M Davis
jmdavisProg at gmx.com
Sun Jun 19 14:15:05 PDT 2011
On 2011-06-19 13:28, Stewart Gordon wrote:
> On 18/06/2011 11:52, Mafi wrote:
> > Am 18.06.2011 10:36, schrieb Jonathan M Davis:
> <snip>
>
> > If anyone ever writes a function which needs immutable chars, toStringz
> > just wroks for it.
>
> <snip>
>
> You mean a C function that keeps the pointer for later use, and relies on
> you not to change it?
That doesn't require immutable at all. And returning const(char)* would work
just as well. You can't alter it in either case. The only way that it would be
alterable would be if the original string which was passed to toStringz wasn't
immutable (e.g. char[]), and the overload of toStringz which took it didn't
make a new array. But the overload of toStringz which takes a char[] _does_
return a new array. So, there is _no_ difference between returning
const(char)* and immutable(char)* unless you have a D function which takes
immutable(char)* that you're trying to pass it to.
Of course, in the case that you're describing, there's always the fun bug that
the GC doesn't know that it needs to hang onto the immutable(char)* which was
returned unless you hold a reference to it somewhere, in which case it could
be collected and screw over the C function which held onto it. Now that I
think about it, it might actually be worth adding a note to the documentation
about that.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list