Skipping a Delphi array by reference

In C ++, you can pass a vector function to a const reference in this way:

void test(const std::vector<int>& a); 

This is useful when the vector is very large, and I want to avoid wasting time copying it. I know the same code in Delphi:

 procedure test(const [Ref] a: array of Integer); 

It also has the same effect as C ++ (pass address instead of copy and optimize / save time)? Is this the only way or is there something else to optimize parameter passing?

+6
source share
2 answers
 procedure test(const a: array of Integer); 

This is an open array passed as const . They are already transmitted by reference. Adding [ref] is useless in this situation.

Only if you pass the open array by value will a copy be made:

 procedure test(a: array of Integer); 

Another option, for completeness, should go through var .

 procedure test(var a: array of Integer); 

Here the array is passed by reference, but, unlike the const array, the compiler allows its contents to be changed.


I know the same code in Delphi ...

This is not entirely accurate. Probably the best mapping from C ++ std::vector<T> is Delphi TList<T> . Probably the closest match to the Delphi open array parameter will be the C ++ array parameter. You can map your Delphi procedure:

 procedure test(const a: array of Integer); 

for this C ++ function:

 void test(const int a[], const size_t len); 

Thus, you really can not compare, for example, as.

However, Delphi dynamic arrays, which you could use when you actually call such a function, are managed types. This means that their lifetime is controlled by automatic reference counting (ARC) and distinguishes them from raw C ++ arrays.

I'm chatting a bit now. Basically I try to understand that the devil is in the details. None of these things fits perfectly between these languages, because languages ​​have subtle differences.

But leaving these nuances aside, if you want to efficiently pass an array to Delphi, then an open const array will achieve this.

+12
source

You are misleading open array parameters and dynamic arrays. There is no need for [Ref] .

The public parameters of the array are actually passed as two parameters.

  • The first contains the address of the first element of the array.
  • The second length of the array (number of elements) minus one, the so-called High() value.

A vector in C ++ is a class. It is passed as a class in Delphi, but the constant is different. In Delphi, even if you pass a class as const , its methods can still be called. In Delphi, class instances are already references. No need for [Ref] .

Additional information about open array parameters in my article .

+7
source

Source: https://habr.com/ru/post/1013178/


All Articles