Create Managed Object in Unmanaged class function

K

Kevin

All samples in Micoroft just mention that if a managed
type is used as a member in nongc class, for example:
gcroot<String*> is used to define a String managed member
variable. What if the managed object in unmanaged class is
just defined in a member function instead of a member
variable. For example:

// managed imports
#using <mscorlib.dll>
using namespace System;
using namespace System::Runtime::InteropServices;

// unmanaged C++ class

class CSimple
{
public:
void Foo();
};

CSimple::Foo()
{
String *test = new String(S"FOO Test");
// Or should test be defined as gcroot<String*>
String nospace = test->Replace(" ", "_");

// Or should nospace be defined as gcroot<String*>
too????

}

it compiles fine without gcroot<String*>, but is it safe
for GC collector, should I define nospace as
gcroot<String*>

Thanks very much for your help!

Kevin
 
E

Edward Diener

Kevin said:
All samples in Micoroft just mention that if a managed
type is used as a member in nongc class, for example:
gcroot<String*> is used to define a String managed member
variable. What if the managed object in unmanaged class is
just defined in a member function instead of a member
variable. For example:

// managed imports
#using <mscorlib.dll>
using namespace System;
using namespace System::Runtime::InteropServices;

// unmanaged C++ class

class CSimple
{
public:
void Foo();
};

CSimple::Foo()
{
String *test = new String(S"FOO Test");
// Or should test be defined as gcroot<String*>

No said:
String nospace = test->Replace(" ", "_");

// Or should nospace be defined as gcroot<String*>
too????

No, see above.
}

it compiles fine without gcroot<String*>, but is it safe
for GC collector, should I define nospace as
gcroot<String*>

No, you are fine.

The reason that gcroot<> is needed for members of a __nogc class is that the
the destruction of an object of a __nogc class, and therefore the release of
a GC pointer in an embedded member, can not normally be tracked by the CLR.
Using gcroot gives the CLR a way to track it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top