properly passing strings to functions? (C++ vs D)

rikki cattermole rikki at cattermole.co.nz
Mon Jan 11 14:23:36 UTC 2021


On 12/01/2021 3:12 AM, 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) { ... }

If you are modifying text the reference and want the caller to see the 
change, use this.

> So the question is does a function call like (ref string ...) 
> (myPrintRef) make any sense in D to avoid additional allocations?

There are no allocations for this.

> A D-Style String could be seen as "const(char)[]"? So as it is a slice 
> it already is a kind of reference to some data elsewhere? Which means 
> calling a function like "myPrint" in D wouldn't cause any allocation. Is 
> this correct?

alias string  = immutable(char)[];

https://github.com/dlang/druntime/blob/master/src/object.d



More information about the Digitalmars-d-learn mailing list