Passing a string by reference
Hipreme
msnmancini at hotmail.com
Tue Nov 8 12:43:06 UTC 2022
On Tuesday, 8 November 2022 at 12:30:50 UTC, Alexander Zhirov
wrote:
> Do I understand correctly that in order for me to pass a string
> when creating an object, I must pass it by value? And if I have
> a variable containing a string, can I pass it by reference?
>
> Should I always do constructor overloading for a type and a
> reference to it?
> In the case of the variable `c`, a drop occurs. Why? An object
> is not being created on the stack?
>
> ```d
> import std.stdio : writeln;
>
> class A
> {
> private string str = "base";
>
> this(ref string str)
> {
> writeln("type reference string");
> this.str = str;
> }
>
> this(string str)
> {
> writeln("type string");
> this.str = str;
> }
>
> this() {}
>
> void print()
> {
> writeln(str);
> }
> }
>
> void main()
> {
> auto a = new A("Hello, World!"); // this type string
> a.print();
> string text = "New string";
> auto b = new A(text); // this type reference string
> b.print();
> A c;
> c.print(); // segmentation fault! Why not "base"?
> }
>
> ```
You forgot to assign "c" to anything, I think you meant:
`A c = b;`
Read that segmentation fault as null pointer exception.
Whenever you assign something to `ref type something`, it will
basically be the same as writing `myVariable = *something;` in C
code, so, in that case, it won't make any difference.
The `ref` attribute only means that if you change your string
inside the code that takes by ref, it will reflect when
returning, such as:
```d
void modifyString(ref string input)
{
input~= "Now it is modified";
}
string text = "New string";
modifyString(text);
writeln(text); //"New stringNow it is modified"
```
More information about the Digitalmars-d-learn
mailing list