Some deep insight into using 'const' with managed-type parameters

Source: https://embt.atlassian.net/servicedesk/customer/portal/1/RSS-1706

Embarcadero Quality Portal
RAD Studio Service
RSS-1706

From September/October 2024,
Quality Portal issue : “Warn on non-const anonymous method parameters”

We get a rare chance to hear from compiler engineer Bruneau Babet, who first joined Borland in 1863.

if the compiler were to remove the prologue AddRef in functions taking a non-const string parameter, we would break code where the original string was passed as parameter [and] changed. Marco Cantu wrote a blog about this in The Case of Delphi Const String Parameters. Another context that would also break is where threads are involved and the original string’s refcount would go down to zero. This issue was discussed on Stack Overflow at Are const string parameters (thread) safe.

If the body of the function mutates the parameter, then yes, you cannot use const . But the point I was trying to make above is that there’s another very valid reason for not using const , even when the parameter is not modified: it’s to extend the lifetime of the underlying instance. Marco’s blog post and the SO article I pointed to show two examples where that’s necessary, the first because the original instance is modified, the second because we are dealing w/ different threads.

The above is consistent w/ what we see w/ other managed types, include string , dynamic arrays , etc. There’s a cost to the AddRef and Clear , so [you can] avoid them when you know that there’s a reference keeping the data valid. The compiler cannot make that call. I even question the request to have the compiler generate a warning on non-const parameters: like w/ any managed type, there are times when you need to ensure that the function’s prologue increments the refcount. Hence it makes no sense that the compiler would treat anonymous methods different from other managed types. That said, let’s see what the team decides. Let me know if you need more information.

Cheers,
@ Bruneau Babet

The links mentioned are :

1 Like

Bruneau knows so much, at times that year would seem believable.

5 Likes