properly passing strings to functions? (C++ vs D)
Q. Schroll
qs.il.paperinik at gmail.com
Tue Jan 12 18:05:41 UTC 2021
On Monday, 11 January 2021 at 14:12:57 UTC, zack wrote:
> A beginner question: How to pass strings properly to functions
> in D?
> Is there any allocation going on if just use a function as
> "myPrint"? In C++ I have often seen calls where one just passes
> a reference/const reference to a string to avoid allocation.
>
> C++:
> void myPrintCPP(const std::string& input){ ... }
>
> D:
> void myPrint(string text){ ... }
> void myPrintRef(ref string text) { ... }
In D, `string` is an abbreviation for the type immutable(char)[],
i.e. slice of immutable char. The slice type is a pointer+length
pair, a (T*, size_t) tuple, it is very lightweight. Using `ref
T[]` (that includes `ref string` aka `ref immutable(char)[]` is
the way if you want reassignments or expanding/shrinking of the
array to be visible to the caller. Since the cost of copying a
pointer and a length is very low, I'd just use this:
void myPrint(string text) { ... }
It'll be probably what you want. Since you cannot write the
immutable characters, if you don't intend to reassign, expand, or
shrink the string locally, you can use `in string text`.
You can basically only read `in` parameters for information. What
`in` buys you is that the compiler will figure out the best way
to pass the object. C++'s const T& will reference always, which
is worse than a copy for small types. D's `in` will copy if the
compiler thinks it's cheaper than referencing. Give
https://dlang.org/changelog/2.094.0.html#preview-in a read, if
you want details about `in`. Use it when it applies. It also
documents intent.
More information about the Digitalmars-d-learn
mailing list