Discussion:
Assignment to "enumerated string", is content copied or array information?
tcak via Digitalmars-d-learn
2014-10-18 23:51:51 UTC
Permalink
enum Values: string{
NONE = "",
Value1 = "Apple",
Value2 = "Peach",
Value3 = "Lemon"
}


Values lastHeldValue = Value3;


Is the "lastHeldValue" just "pointer + length" information, and it
points to "Lemon"; or is "Lemon" copied to another place in
memory?

I am doing comparison as "if( lastHeldValue == Value3 )" and am
not
sure what comparison operation it is doing in the background.
Meta via Digitalmars-d-learn
2014-10-19 02:00:20 UTC
Permalink
Post by tcak via Digitalmars-d-learn
enum Values: string{
NONE = "",
Value1 = "Apple",
Value2 = "Peach",
Value3 = "Lemon"
}
Values lastHeldValue = Value3;
Is the "lastHeldValue" just "pointer + length" information, and it
points to "Lemon"; or is "Lemon" copied to another place in
memory?
I am doing comparison as "if( lastHeldValue == Value3 )" and am
not
sure what comparison operation it is doing in the background.
The value will be "copied and pasted" where you use a Values.
However, strings are cached in D, so the following problem will
print "true" for both checks.

import std.stdio;

void main()
{
enum s = "test";
auto v1 = s;
auto v2 = s;

//Check that both point to the same string in memory
writeln(v1 is v2);

//Check that both have the same value
writeln(v1 == v2);
}

Because enum values are copied and pasted, it is usually a bad
idea to make an enum that contains arrays or classes, as
everywhere you use the enum values allocates a new array/object.
With strings it's okay, as they're cached.

Loading...