简体   繁体   中英

delete a managed object c++/cli

How can i delete a managed Object in c++/cli? it is a bit Special.

A Example:

//.h
ref class Myclass
{
public:
static Myclass^ GetInstance(void); 


private:
    static Myclass ^m_hInstance;
}

//.cpp
Myclass^ Myclass::GetInstance(void)
{
    if (m_hInstance == nullptr)
    {
        System::Windows::MessageBox::Show("mknew");
        m_hInstance = gcnew Myclass();
    }

    return m_hInstance;

}
.
.
.

so i can use in all my Win32 DLL-functions

Myclass::GetInstance()->MyFunction();

that works without any Problems, but i need to "reset" it - creating a new instance (and kill the old one) i tryed:

- delete Myclass::GetInstance(); (outside)
- delete m_hInstance; (inside class with a shutdown function)
- added a (empty) ~Destructor
- Myclass::GetInstance()->Dispose() (this wont work, not a Member)

(and after all GC::Collect())

The only way was, to set

m_hInstance = nullptr;

but the old Object will not die, for Example, files that were opened by the old object were locked until i exited the app.

For managed objects in C++/CLI, you have no control over the object destruction timing. Using gcnew means that you consent to have your memory managed by the garbage collector, which will stick to its own schedule, and will release your stuff (and call your finalizers) when it pleases.

The .NET Framework has an IDisposable interface to deal with this kind of situation. Disposable objects have a Dispose() method that you can call to release the resources that they own. The point of this pattern is to put you back in control of resources (like files) that you can't afford to have cleaned up non-deterministically.

Instead of just setting your instance to nullptr (which you still need to do), you'll call the Dispose method on it first. This method is responsible for closing all the handles your object owns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM