I’ve come across something in C++/CLI that goes against what I thought I knew:
Usually, if you pass an object into a function, you’d use a dot to access its methods (this also works for ref classes, with some extra constructors):
value class Value {
void Print() { Console::WriteLine("Value"); }
};
void f(Value v) {
v.Print();
}
Also usually, passing an object via an interface into a function forces you to put a ^ on the argument, and use -> in the method call:
interface class Base {
void Print();
};
void f(Base ^b) {
b->Print();
}
However, if you make f generic, with a constraint based on an interface, the compiler insists that you use ->, but also insists you don’t use ^ in the arguments list:
interface class Base {
void Print();
};
generic <class T> where T : Base
void f(T t) {
t->Print();
}
Up to now, I believed that referencing objects directly always uses . and referencing them through their handles always uses ->. This appears to reference an object directly using a -> – what am I getting wrong?
They tried to make the C++/CLI syntax equivalent to C++ syntax but that wasn’t particularly successful. The rule is that you use
.to access a member of a value type,->to a access a member of a reference type.Complication number one is stack semantics. You can drop the hat to declare a local variable of a reference type. Which then automatically gets disposed at the end of the scope block, the compiler automatically generates a destructor call. An attempt to make managed types behave similar to C++ types and rescue the RAII pattern.
Complication number two is that the compiler permits using the hat on a variable of a value type. Which is 99% of the type a mistake, particularly nasty because that’s very expensive at runtime since the value gets boxed.
Generics made it ultimately ambiguous, the type parameter can be either a value type or a reference type. Which will make the concrete type either a value or a reference type, that isn’t sorted out until runtime. Note that this is permitted in your example, a value type may implement an interface. The rule then is that you always write the code without hats on the variables of the type parameter, treating them as through they are value types. But dereference those variables as though they were reference type references, using the arrow. Yes, very confusing.