The question is why compiler make copy of a string?
This code demonstrate a problem when use something else than constref. It would be nice if compiler have an option to turn off such hidden copying.
{$mode objfpc}{$H+} procedure P1(constref Ch: AnsiChar); begin Writeln('P1 Char'); end; procedure P1(constref Ch: WideChar); begin Writeln('P1 Wide'); end; procedure P2(P: PAnsiChar); begin Writeln('P2 Char'); end; procedure P2(P: PWideChar); begin Writeln('P2 Wide'); end; var S: AnsiString = '12345'; W: WideString = '12345'; begin P1(S[1]); P1(W[1]); P2(@S[1]); P2(@W[1]); Writeln('1'); end.
Did you check the assembler output?
This can be solved by using {$TYPEDADDRESS ON} aka {$T+}Is this going to work when I place procedures in separate unit or whole project should be compiled with this switch?
I need a reference.it is the link that is needed - use only the Pointer type. I always do that. And you always know exactly what you have.
A separate unit is enough.QuoteThis can be solved by using {$TYPEDADDRESS ON} aka {$T+}Is this going to work when I place procedures in separate unit or whole project should be compiled with this switch?
QuoteThis can be solved by using {$TYPEDADDRESS ON} aka {$T+}Is this going to work when I place procedures in separate unit or whole project should be compiled with this switch?
Interestingly, the discussion turned to another issue, not the one stated in the topic.
P2 CharThis mean all project should be built with {T+} option. This also mean we can't use overloaded functions in units that rely on strings.
P2 Wide
P2 Char
P2 Char
This mean all project should be built with {T+} option. This also mean we can't use overloaded functions in units that rely on strings.You've mixed two different things.
I think behavior of compiler around constref should be changed. As I suppouse idea of constref is that we reference something, but not change it. So compiler should not do copy of a string on constref.
Can anyone show an example when copying a string on constref is a necessery move?
Putting aside the discussion whether constref should copy the underlying string, what exactly are you trying to do?
And then, if the string is protected because "constref" takes a pointer (reference) to a char in the string, then why is it not protected ifThis express my point very well. It is illogical that constref protect when taking a pointer, but taking a pointer not protect.
It all depends on the level of optimization, and other settings. Maybe even compiler version.Optimization should never affect result.
It all depends on the level of optimization, and other settings. Maybe even compiler version.Optimization should never affect result.
Do trunk have this problem?
Should I report this to bugtracker?
This mean all project should be built with {T+} option.
The same as I indicated above, only my version is more optimal, but @LemonParty rejected it.
P1(pchar(S)[0]);