What is the difference between开发者_运维问答 the following two functions?
ref class SomeClass;
void swap(SomeClass^& a, SomeClass^& b){
SomeClass^ c = a;
a = b;
b = c;
}
void swap2(SomeClass^% a, SomeClass^% b){
SomeClass^ c = a;
a = b;
b = c;
}
The main difference between a reference and a tracking reference is, that the tracking reference is allowed to be moved by the garbage collection.
During the run of the gc, objects are moved around. If you access an object after it is moved by it's adress, you read garbadge. That's where the tracking handle comes in. It is aware of the gc and its object moving. You can still access the object after it has been moved.
From MSDN:
A tracking reference is similar to a C++ reference, to specify that a variable is passed to a function by reference and to create an alternative name for an object. However, the object referenced by a tracking reference can be moved during execution by the common language runtime garbage collector.
I don't know if taking a reference (&) of an gc-object stops it from being moved by the gc.
My guess is that the 2nd case cannot be used from outside C++/CLI (e.g., VB, C#, etc.), whilst the first can. I didn't try it, though.
精彩评论