在C ++中删除对象 [英] Deleting an object in C++

查看:106
本文介绍了在C ++中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是一个示例代码:

void test()
{
   Object1 *obj = new Object1();
   .
   .
   .
   delete obj;
}

我在Visual Studio中运行它, obj;'。
这不是正常的方式来释放与对象相关的内存吗?
我意识到它会自动调用析构函数...这是正常的吗?

I run it in Visual Studio, and it crashes at the line with 'delete obj;'. Isn't this the normal way to free the memory associated with an object? I realized that it automatically invokes the destructor... is this normal?

这里是一个代码片段:

    if(node->isleaf())
    {
        vector<string> vec = node->L;
        vec.push_back(node->code);
        sort(vec.begin(), vec.end());

        Mesh* msh = loadLeaves(vec, node->code);

        Simplification smp(msh);

        smp.simplifyErrorBased(errorThreshold);

        int meshFaceCount = msh->faces.size();

        saveLeaves(vec, msh);

        delete msh;
    }

loadleaves()是一个从磁盘读取网格并创建 Mesh 对象并返回它的函数(考虑 vec code> node-> code 只是关于要打开的文件的信息)

loadleaves() is a function that reads a mesh from disk and creates a Mesh object and returns it.(think of vec and node->code are just information about the file to be opened)

c> delete msh; line?

Should I remove the delete msh; line?

推荐答案

释放与对象相关联的内存的正常方式?

Isn't this the normal way to free the memory associated with an object?

这是管理动态分配的内存的常见方法,但它不是好的方法这样做。这种代码很脆弱,因为它不是异常安全的:如果在创建对象和删除对象之间抛出异常,你将泄漏该对象。

This is a common way of managing dynamically allocated memory, but it's not a good way to do so. This sort of code is brittle because it is not exception-safe: if an exception is thrown between when you create the object and when you delete it, you will leak that object.

最好使用智能指针容器,你可以使用它来获取范围绑定的资源管理(更常见的是,或者RAII)。资源获取是资源获取的初始化。

It is far better to use a smart pointer container, which you can use to get scope-bound resource management (it's more commonly called resource acquisition is initialization, or RAII).

作为自动资源管理的示例:

As an example of automatic resource management:

void test()
{
    std::auto_ptr<Object1> obj1(new Object1);

} // The object is automatically deleted when the scope ends.

根据您的用例, auto_ptr 不提供你需要的语义。在这种情况下,您可以考虑使用 shared_ptr

Depending on your use case, auto_ptr might not provide the semantics you need. In that case, you can consider using shared_ptr.

至于为什么当您删除对象时程序崩溃,你没有给予足够的代码,任何人都能够肯定地回答这个问题。

As for why your program crashes when you delete the object, you have not given sufficient code for anyone to be able to answer that question with any certainty.

这篇关于在C ++中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆