| title | auto_gcroot::attach | Microsoft Docs | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| ms.custom | ||||||||||||||
| ms.date | 11/04/2016 | |||||||||||||
| ms.reviewer | ||||||||||||||
| ms.suite | ||||||||||||||
| ms.technology |
|
|||||||||||||
| ms.tgt_pltfrm | ||||||||||||||
| ms.topic | reference | |||||||||||||
| f1_keywords |
|
|||||||||||||
| dev_langs |
|
|||||||||||||
| helpviewer_keywords |
|
|||||||||||||
| ms.assetid | 996ede65-bcb5-41f2-bfbf-507f8a578241 | |||||||||||||
| caps.latest.revision | 12 | |||||||||||||
| author | mikeblome | |||||||||||||
| ms.author | mblome | |||||||||||||
| manager | ghogen | |||||||||||||
| translation.priority.ht |
|
Attach auto_gcroot to an object.
auto_gcroot<_element_type> & attach(
_element_type _right
);
auto_gcroot<_element_type> & attach(
auto_gcroot<_element_type> & _right
);
template<typename _other_type>
auto_gcroot<_element_type> & attach(
auto_gcroot<_other_type> & _right
);
_right
The object to attach, or an auto_gcroot containing the object to attach.
The current auto_gcroot.
If _right is an auto_gcroot, it releases ownership of its object before the object is attached to the current auto_gcroot.
// msl_auto_gcroot_attach.cpp
// compile with: /clr
#include <msclr\auto_gcroot.h>
using namespace System;
using namespace msclr;
ref class ClassA {
protected:
String^ m_s;
public:
ClassA( String^ s ) : m_s( s ) {
Console::WriteLine( "in ClassA constructor:" + m_s );
}
~ClassA() {
Console::WriteLine( "in ClassA destructor:" + m_s );
}
virtual void PrintHello() {
Console::WriteLine( "Hello from {0} A!", m_s );
}
};
ref class ClassB : ClassA {
public:
ClassB( String ^ s) : ClassA( s ) {}
virtual void PrintHello() new {
Console::WriteLine( "Hello from {0} B!", m_s );
}
};
int main() {
auto_gcroot<ClassA^> a( gcnew ClassA( "first" ) );
a->PrintHello();
a.attach( gcnew ClassA( "second" ) ); // attach same type
a->PrintHello();
ClassA^ ha = gcnew ClassA( "third" );
a.attach( ha ); // attach raw handle
a->PrintHello();
auto_gcroot<ClassB^> b( gcnew ClassB("fourth") );
b->PrintHello();
a.attach( b ); // attach derived type
a->PrintHello();
}
in ClassA constructor:first
Hello from first A!
in ClassA constructor:second
in ClassA destructor:first
Hello from second A!
in ClassA constructor:third
in ClassA destructor:second
Hello from third A!
in ClassA constructor:fourth
Hello from fourth B!
in ClassA destructor:third
Hello from fourth A!
in ClassA destructor:fourth
Header file <msclr\auto_gcroot.h>
Namespace msclr
auto_gcroot Members
auto_gcroot::operator=
auto_gcroot::release