Boris
Boris

Reputation: 8941

Why can't tracking references be used as class members?

The following code:

ref class A
{
private:
  int% referenceToAnInt;
};

produces the following error in Visual Studio:

error C3160: 'int %' : a data member of a managed class cannot have this type

I thought tracking references were a managed thing - so why can't they be a member of a managed class? Also: How would I store a reference to a value type in C++/CLI correctly?

Upvotes: 3

Views: 599

Answers (2)

svick
svick

Reputation: 244848

Tracking references are “managed thing” which is why you can't use them as a member of a class. They are similar to C++ & references in that you can use them to refer to local variables in some other method. But local variables are stored in the short term store (a.k.a. the stack). That means that when the method that contains that local variable ends, the reference wouldn't be valid anymore, but the object could still exist.

This would not be memory-safe, which is why doing this is forbidden in .Net.

Upvotes: 2

Botz3000
Botz3000

Reputation: 39620

The CLR doesn't allow storing tracking references as fields. Also, from the C++/CLI-Spec:

A program containing a tracking reference that has storage duration other than automatic is ill-formed. (This precludes having a tracking reference as a data member.)

I guess they wanted to avoid the problem where you keep a reference longer than the actual lifetime of the referenced object. An alternative would be to use a wrapper ref class to hold the value, or delegates for reading / writing.

Upvotes: 4

Related Questions