Return ref struct

  • Thread starter Thread starter Maxim
  • Start date Start date
M

Maxim

Hi all,

Why is the following code doesn't work?


public ref struct MyType
{
..................
};

MyType GetMyType()
{
MyType result;
......................
return result;
}

The compiler says

Error 3 error C2440: 'return' : cannot convert from 'MyLib::MyType' to
'MyLib::MyType'

Thanks in advance
 
After changing this to

public ref struct MyType
{
.................
};

MyType ^ GetMyType()
{
MyType result;
.....................
return %result;
}

This code compiles without errors.

But to the best of my knowledge this involves boxing procedure. Is it
possible to avoid it in this case?
 
Maxim said:
After changing this to

public ref struct MyType
{
................
};

MyType ^ GetMyType()
{
MyType result;
....................
return %result;
}

This code compiles without errors.

But to the best of my knowledge this involves boxing procedure. Is it
possible to avoid it in this case?

It's a reference type, so no boxing is performed. The local variable isn't
actually on the stack, it has stack semantics (your Dispose method, if any,
will be called when the function exits even though you return the value,
which is a different flavor of the native C++ problem if you try to return a
reference to a non-static local variable).
 
Back
Top