properly passing strings to functions? (C++ vs D)
IGotD-
nise at nise.com
Mon Jan 11 16:53:50 UTC 2021
On Monday, 11 January 2021 at 14:12:57 UTC, zack wrote:
>
> D:
> void myPrint(string text){ ... }
> void myPrintRef(ref string text) { ... }
>
In D strings are immutable so there will be no copying when
passing as function parameters. Strings are essentially like
slices when passing them.
I usually use "const string text" because D has no implicit
declaration of variables. So using "ref" will not create a
variable. This is contrary to C++ where passing as "const
std::string &text" has a performance benefit and also C++ creates
a unnamed variable for you.
ex.
void myFunction1(const string text);
void myFunction2(const ref string text);
myFunction1("test");
myFunction2("test"); -------> error cannot create an implicit
reference
then you have to do like this
string t = "text";
myFunction2(t);
This will work but you have to do the extra step by declaring t.
Annoying as you cannot write text literals directly in the
function parameters, therefore I do not use "ref" and it doesn't
have a big benefit in D either.
More information about the Digitalmars-d-learn
mailing list