What does the C++/CLI Object^% (caret percent-sign

2019-02-03 04:13发布

问题:

This apparently is a Google-proof term since I can't get any search engines to not throw away the "extra" characters. I did also look on MSDN in the C++ reference but I can't seem to find the C++/CLI reference because there is nothing in the declarations section on it.

回答1:

% is a tracking reference.

It is similar to a native reference (Object&), but a tracking reference can reference a CLR object while a native reference cannot. The distinction is necessary because the garbage collector can move CLR objects around, so a CLR-object's memory address may change.

The ^ simply means it is managed. See MSDN and also this SO post.



回答2:

It means "pass by reference":

 void bar::foo(Object^% arg) {
    arg = gcnew Object;    // Callers argument gets updated
 }

Same thing in C++:

 void foo(Object** arg) {
    *arg = new Object;
 }

or C#:

 void foo(out object arg) {
     arg = new Object();
 }

C++/CLI doesn't distinguish between ref and out, it does not have the definite assignment checking feature that the C# language has so no need to distinguish between the two. Same in VB.NET, ByRef vs ByVal.



回答3:

Essentially, it's the "managed" version of Object*&, and equivalent to ref or out on a reference type in C#.



回答4:

This is a managed pointer by reference. So if you had something like:

void DoSomething(System::String^% stringObject)

in C# it would look like:

void DoSomething(ref System.String stringObject)


回答5:

This is a C++/CLI Tracking Reference. This is kind of like a C++ reference, but to a managed object.



标签: c++-cli