简体   繁体   English

删除托管对象c ++ / cli

[英]delete a managed object c++/cli

How can i delete a managed Object in c++/cli? 如何在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 所以我可以在我所有的Win32 DLL函数中使用

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()) (以及毕竟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. 对于C ++ / CLI中的托管对象,您无法控制对象销毁的时间。 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. 使用gcnew意味着您同意由垃圾收集器来管理内存,垃圾收集器将按照自己的时间表进行调度,并在需要时释放您的东西(并调用终结器)。

The .NET Framework has an IDisposable interface to deal with this kind of situation. .NET Framework具有IDisposable接口来处理这种情况。 Disposable objects have a Dispose() method that you can call to release the resources that they own. 一次性对象具有一个Dispose()方法,您可以调用该方法来释放它们拥有的资源。 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. 不仅将实例设置为nullptr (您仍然需要这样做), 需要首先在其上调用Dispose方法。 This method is responsible for closing all the handles your object owns. 此方法负责关闭对象拥有的所有句柄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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