Passing a string by reference
Alexander Zhirov
azhirov1991 at gmail.com
Tue Nov 8 12:30:50 UTC 2022
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"?
}
```
More information about the Digitalmars-d-learn
mailing list