Automatic management of dynamic arrays in functions that return elements

 

According to the documentation: "Dynamic arrays are automatically freed when going beyond the visibility area of the block they are declared in."

But what occurs when an element in the dynamic array is returned by a function? How will MQL5 knows that it should not deallocate the memory of the returned element?


For example:

string example() {

        string str = "a,b,c,d";
        string dynamicArray[];
        StringSplit(str, ',', dynamicArray);
        return dynamicArray[0];
}


int OnInit() {
        
        Print(example()); // Output: a
        return INIT_FAILED;
}

So "dynamicArray" will be deallocated when the function returns. But what occurs to the memory of dynamicArray[0] ? It should not be deallocated if used outside the function.

Or does MQL5 returns string by value? Then it will make a copy of dynamicArray[0] before returning.

 
BB-8:

Or does MQL5 returns string by value? Then it will make a copy of dynamicArray[0] before returning.

yes

 
BB-8: But what occurs when an element in the dynamic array is returned by a function?

You returned a copy of the element. The array is irrevalent.

 
Thanks for the answers.

I find the return by value confusing when using a string (because in C a string is a char* ; or it can be std::string in C++). In this case it is an array of strings to complicate further.

C++ pointer to objects which go out of scope when function returns - why does this work?
C++ pointer to objects which go out of scope when function returns - why does this work?
  • 2013.05.16
  • Angus Comber Angus Comber 7,720 9 9 gold badges 46 46 silver badges 88 88 bronze badges
  • stackoverflow.com
Both these calls to get_string and get_string2 return objects which go out of scope when the function returns. Shouldn't the returned object be an address in memory which goes out of scope after the function returns? This is using Visual Studio 2008. Should this always work? Why?
 
William Roeder:

You returned a copy of the element. The array is irrevalent.

Who deleted my comment? He's always correcting people, and here, he's misleading the OP. It's 'irrelevant'. https://www.spellchecker.net/misspellings/irrevalent
 
Anonymous3 Geek:
Who deleted my comment? He's always correcting people, and here, he's misleading the OP. It's 'irrelevant'. https://www.spellchecker.net/misspellings/irrevalent

I deleted your irrelevant comment -

@Anonymous3 Geek - if you want to say something valuable so - say.
if not - your irrelevant/flooding comments will be deleted and you will be banned.