auto_gcroot::auto_gcroot
The latest version of this topic can be found at auto_gcroot::auto_gcroot.
The auto_gcroot
constructor.
Syntax
auto_gcroot(
_element_type _ptr = nullptr
);
auto_gcroot(
auto_gcroot<_element_type> & _right
);
template<typename _other_type>
auto_gcroot(
auto_gcroot<_other_type> & _right
);
Parameters
_ptr
The object to own.
_right
An existing auto_gcroot
.
Remarks
When constructing an auto_gcroot
from an existing auto_gcroot
, the existing auto_gcroot
releases its object before transferring ownership of the object to the new auto_gcroot
.
Example
// msl_auto_gcroot_auto_gcroot.cpp
// compile with: /clr
#include <msclr\auto_gcroot.h>
using namespace System;
using namespace msclr;
ref class RefClassA {
protected:
String^ m_s;
public:
RefClassA(String^ s) : m_s(s) {
Console::WriteLine( "in RefClassA constructor: " + m_s );
}
~RefClassA() {
Console::WriteLine( "in RefClassA destructor: " + m_s );
}
virtual void PrintHello() {
Console::WriteLine( "Hello from {0} A!", m_s );
}
};
ref class RefClassB : RefClassA {
public:
RefClassB( String^ s ) : RefClassA( s ) {}
virtual void PrintHello() new {
Console::WriteLine( "Hello from {0} B!", m_s );
}
};
class ClassA { //unmanaged class
private:
auto_gcroot<RefClassA^> m_a;
public:
ClassA() : m_a( gcnew RefClassA( "unmanaged" ) ) {}
~ClassA() {} //no need to delete m_a
void DoSomething() {
m_a->PrintHello();
}
};
int main()
{
{
ClassA a;
a.DoSomething();
} // a.m_a is automatically destroyed as a goes out of scope
{
auto_gcroot<RefClassA^> a(gcnew RefClassA( "first" ) );
a->PrintHello();
}
{
auto_gcroot<RefClassB^> b(gcnew RefClassB( "second" ) );
b->PrintHello();
auto_gcroot<RefClassA^> a(b); //construct from derived type
a->PrintHello();
auto_gcroot<RefClassA^> a2(a); //construct from same type
a2->PrintHello();
}
Console::WriteLine("done");
}
in RefClassA constructor: unmanaged
Hello from unmanaged A!
in RefClassA destructor: unmanaged
in RefClassA constructor: first
Hello from first A!
in RefClassA destructor: first
in RefClassA constructor: second
Hello from second B!
Hello from second A!
Hello from second A!
in RefClassA destructor: second
done
Requirements
Header file <msclr\auto_gcroot.h>
Namespace msclr
See Also
auto_gcroot Members
auto_gcroot::attach
auto_gcroot::operator=
auto_gcroot::~auto_gcroot