procedure test(const a: array of Integer);
This is an open array, passed as const
. These are already passed by reference. Adding [ref]
in this situation is needless.
Only if you pass an open array by value will a copy will be made:
procedure test(a: array of Integer);
The other option, for sake of completeness, is to pass by var
.
procedure test(var a: array of Integer);
Here the array is passed by reference, but, in contrast to the const
array, the compiler permits its content to be modified.
I know that the same code in Delphi is ...
That's not quite accurate. Probably the best mapping from C++ std::vector<T>
is to Delphi's TList<T>
. Probably the closest match to a Delphi open array parameter would be a C++ array parameter. You might map your Delphi procedure:
procedure test(const a: array of Integer);
to this C++ function:
void test(const int a[], const size_t len);
So you aren't really comparing like for like.
That said, Delphi dynamic arrays, which you might well be using when you actually call such a function, are managed types. This means that their lifetimes are managed by automatic reference counting (ARC) and that sets them apart from raw C++ arrays.
I'm rambling somewhat now. Mostly what I am trying to get at is that the devil is in the details. None of these things map perfectly between these languages because the languages have their subtle differences.
But, leaving these nuances aside, if you wish to pass an array efficiently in Delphi, then a const
open array will achieve that.
[Ref]
here. Open array parameters are passed as two parameters. The first one contains the address of the first element of the array. The second one the length of the array (numer of elements) minus one, the so called High() value. – Peroneusprocedure test(const a: TArray<integer>);
– Kuhlstd::vector<int>& a
and open arrayarray of Integer
being the same concept in the context, expressed by means of different languages. That is not the EVIDENCE that he thinks his Pascal quotation features a dynamic array, it is not. But quite a hint. – Kuhltype T3DPoint = record X,Y,Z: double end;
can well usetype T3DPoint = array[1..3] of double;
instead. I remember i did it. So, shame for me for overlooking this perfectly valid niche. Still the rule of thumb holds, when one can validate choice of niche tools (like the opt-in criteria you listed: if vector and if fixed size vector and if fixed size that never would change vector and if never-change fixed length vector passed by value) then he has a valid reason to start using them. – Kuhl