October 18, 2014 Assignment to "enumerated string", is content copied or array information? | ||||
|---|---|---|---|---|
| ||||
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.
| ||||
October 19, 2014 Re: Assignment to "enumerated string", is content copied or array information? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to tcak | On Saturday, 18 October 2014 at 23:51:53 UTC, tcak wrote:
> 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.
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply