I’m using C++/CLI Visual Studio 2010 Professional.
Consider this simple native pure C++ code.
1 2 3 4 5
|
int nmbr = 5;
int *nmbrPtr = &nmbr;
Subroutine_1(nmbrPtr); // or Subroutine_1(&nmbr);
// Since a pointer to the variable is passed,
// the subroutine can change the value of nmbr.
|
Now consider this managed C++/CLI code.
1 2 3 4 5
|
int nmbr = 5;
int ^nmbrHdl = &nmbr; // Error!
int ^nmbrHdl = %nmbr; // Error!
Subroutine_2(nmbr);// Only the value 5 is passed.
// The subroutine can’t change the value of nmbr.
|
The following seems to kind of work.
1 2 3 4
|
void Subroutine_3(int %n) { n++; }
int nmbr = 5;
nmbr++; // nmbr has incremented from 5 to 6
Subroutine_3(nmbr); // nmbr has incremented from 6 to 7.
|
Is that correct? Is that the “proper” way? What is going on here?
What is being passed by Subroutine_3(nmbr)? Looks like only the value 6 is being passed, just like the example in Subroutine_2(nmbr) above.
Which of the following is correct?
1 2 3 4 5 6
|
void Subroutine_4(int ^%n) { *n = 1; } // ^%
void Subroutine_5(int ^n) { *n = 2; } // ^ only
int ^num = gcnew int;
*num = 0;
Subroutine_4(num);
Subroutine_5(num);
|
According to pages 26-27 here,
http://aspalliance.com/chapters/chapters/1932394818/1932394818_chapter1.pdf
you must use tracking reference to a handle, so only Subroutine_4 is correct, and Subroutine_5 is wrong.
However, they both seem to work.