вторник, 23 мая 2017 г.

Смешно. "Смешит" и Embarcadero и Штефан Глинке

It just occured to me that when I have such code:

TFooBar = class
s: string;

procedure Main;
x, y: TFooBar;
x := TFooBar.Create;
y := TFooBar.Create;

x.s := 'True';
y.s := 'True';

Assert(Pointer(x.s) = Pointer(y.s));


The assertion will raise because whenever you assign a string literal to a string variable it checks if the string is a const (refcount = -1) and then calls _NewUnicodeString). I guess this has been discussed already somewhere else but I cannot find anything regarding my question:

I would guess that even if it is a const it could assign that reference to s and don't touch the refcount. This should work fine with the cow mechanics.

But as it is this would mean that if code runs through such const string assignments every time a new string gets allocated, no?
In my case I am using the const string 'True' for nullables in Spring to set the "HasValue" flag for them (otherwise the field is empty). However by using a const there it creates a new string every time. So if you have 10 nullable values you have 10 string instances with the content "True". The only solution I found so far was to make the const a variable (in this case it works because its private) and assign 'True' to it in the initialization section (or could also in the class ctor). That way there is only one string instance with content 'True' for the nullables around.

Any other solution I am missing?

Edit: I found this SO question:
https://stackoverflow.com/questions/12837129/string-const-why-different-implementation-for-local-and-result so I changed the original example to use objects and non global variables.

In my case I know that the module the literal is coming from will not be unloaded before anyone that is using it. That makes me think if we would need some kind of const string with start refcount = 1. Since its a const you could not modify it (which would modify the const because of refcount 1) but when assigning somewhere the same reference is being used and no new strings are being produced. I guess I am missing some cornercases why this is not possible -.- So I probably will use the hidden string variable to get the same result.

Комментариев нет:

Отправить комментарий