Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an argument by reference in C++/CLI so re-assignment affects the caller

Probably this is not a difficult question, but I am always a little bit confused on how to treat String type as an argument in Visual C++. I have the following to functions:

void function_1(String ^str_1)
{
  str_1 = gcnew String("Test");
}

void function_2()
{
  String ^str_2 = nullptr;
  function_1(str_2);
}

After calling function_1, str_2 is still equal to null, but what I want to achieve is that str_2 is equal to Test. So, how can I achieve that the content of str_1 is passed to function_2?

Thanks for any advice.

like image 803
stefangachter Avatar asked Jun 17 '10 08:06

stefangachter


People also ask

What happens when an argument is passed by reference?

When you pass an argument by reference, you pass a pointer to the value in memory. The function operates on the argument. When a function changes the value of an argument passed by reference, the original value changes. When you pass an argument by value, you pass a copy of the value in memory.

Are arguments passed by reference in C?

Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. In C, the corresponding parameter in the called function must be declared as a pointer type.

How arguments are passed to a function using references?

The call by reference method of passing arguments to a function copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.

Which syntax is correct for call by reference in C for fun?

int main() { int x=100; printf("Before function call x=%d \n", x);


1 Answers

Use a tracking reference:

void function_1(String ^%str_1)
{
  str_1 = gcnew String("Test");
}

Explanation: Passing String ^ is like passing a pointer. Changes are only made to the local copy of the reference. String ^% is like passing a reference to a reference... just as you would pass a pointer to a pointer when calling a function that should change the original pointer.

like image 122
Agnel Kurian Avatar answered Sep 27 '22 21:09

Agnel Kurian