C++ 中的析构函数

发布于 2024-11-08 02:47:50 字数 607 浏览 0 评论 0原文

我制作了一个头文件,其中包含一个名为 cmysqldb 的类,其中包含很多指针。 我现在的问题是:

我如何创建一个析构函数来删除可能导致潜在内存泄漏的指针?

这是标题代码:

#ifndef CMSYQLDB_H
#define CMSYQLDB_H

#include <QMultiMap>
#include <QStringList>
#include "mysql.h"

class cmysqldb
{

public:
    cmysqldb::~cmysqldb()
    {
        const char *text,
        MYSQL *connection,
        MYSQL_RES *result,
        MYSQL_RES *fresult,
        MYSQL_FIELD *mfield
    }
    int query_state;
    int numfields;
    MYSQL mysql;
    MYSQL_ROW row;
    MYSQL_ROW fieldrow;


   ....


};


#endif // CMSYQLDB_H

这是你的意思吗???

I had made a header file with a class named cmysqldb with a lot of pointers.
My problem is now this:

How could i create a destructor that will delete the pointers that may cause potential memory leak?

here is the header code:

#ifndef CMSYQLDB_H
#define CMSYQLDB_H

#include <QMultiMap>
#include <QStringList>
#include "mysql.h"

class cmysqldb
{

public:
    cmysqldb::~cmysqldb()
    {
        const char *text,
        MYSQL *connection,
        MYSQL_RES *result,
        MYSQL_RES *fresult,
        MYSQL_FIELD *mfield
    }
    int query_state;
    int numfields;
    MYSQL mysql;
    MYSQL_ROW row;
    MYSQL_ROW fieldrow;


   ....


};


#endif // CMSYQLDB_H

is this what you mean???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

寒江雪… 2024-11-15 02:47:50

通过 new 获取的资源应使用 delete 进行释放,而使用 new[] 则应使用 delete[] 进行释放。就这么简单,避免内存泄漏。如果您发布更具体的代码可能会更有帮助。

析构函数与类具有相同的名称,只是前面有一个 ~ 符号。

cmysqldb :: ~cmysqldb()
{
    // deallocate the resources with the above mentioned rule 
}

class foo
{
    int var ;
    int *ptr ;

    public:

        foo()
        {
             ptr = new int ;
        }

        ~foo()
        {
             delete ptr ;
        }
};

void bar()
{

    foo obj ;

    // .....

} // <-- obj goes out of scope and it's destructor is called at this point.

foo类有两个分别为int、int*类型的成员变量var、ptr。因此,在 var 中保存整数所需的字节以及可以指向整数地址的指针(ptr) 是自动分配的。这些资源不是我们分配的。因此,我们没有责任重新分配这些资源。到目前为止,一切都很好。

ptr = new int ;

new int 从可以保存 int 的免费存储中获取资源,并返回 ptr 保存的地址。现在,从免费存储中获取资源是因为用户定义的new操作。因此,用户的工作就是将资源返回到免费商店。因此,析构函数中的语句 -

delete ptr ;

The Definitive C++ Book Guide 获取一本书,并且List 甚至可以更好地解释。另请遵循@Michael 建议,使用自动管理资源的智能指针。

Resources acquired through new should be deallocated using delete and with new[] should be with delete[]. As simple as that to avoid memory leaks. Could be more helpful if you post more specific code.

Destructor bears the same name of the class, except that it has a ~ symbol before it.

cmysqldb :: ~cmysqldb()
{
    // deallocate the resources with the above mentioned rule 
}

class foo
{
    int var ;
    int *ptr ;

    public:

        foo()
        {
             ptr = new int ;
        }

        ~foo()
        {
             delete ptr ;
        }
};

void bar()
{

    foo obj ;

    // .....

} // <-- obj goes out of scope and it's destructor is called at this point.

foo class has two member variables var, ptr of type int, int* respectively. So, bytes required to hold an integer in var and pointer(ptr) that can point to an integer's address is automatically allocated. These resources are not allocated by us. So, it's not our responsibility to deallocates these resources. So far so good.

ptr = new int ;

new int acquires resources from the free store that can hold an int and it's address is returned which ptr holds. Now, this acquisition of resource from free store is because of the new operation defined by the user. So, it's the job of the user to return the resources back to the free store. So, the statement in the destructor -

delete ptr ;

Get a book from The Definitive C++ Book Guide and List which can even explain better. Also follow @Michael advice of using smart pointers which manages resources automatically.

川水往事 2024-11-15 02:47:50

为了删除指针,您需要将它们存储在某个地方。目前尚不清楚您在哪里执行此操作(您没有构造函数接受的所有指针参数的字段),因此我无法为您提供执行此操作的确切代码,但我将列出您如何执行此操作继续这样做......

要声明析构函数,请将以下内容添加到您的类声明中:

~cmysqldb();

请注意,如果您的类将有任何虚拟方法,您应该将其声明为:

virtual ~cmysqldb();

在源文件中添加:

cmysqldb::~cmysqldb()
{
    // contents of your destructor goes here.
}

现在,如何您释放资源的具体情况取决于它们的分配方式。如果您使用了一些特定于库的创建函数,并且有一个特定于库的免费函数,那么就使用它。如果使用 malloc 分配,则使用 免费;如果是用new分配的,则使用delete;如果它是使用new[]分配的,则使用delete[]。另外,您应该使用智能指针类,例如 boost::scoped_ptr< /a> (std::unique_ptr) 或 boost::shared_ptr< /a> (std::shared_ptr),尽可能避免在构造函数/析构函数中通过 new/delete 显式管理这些资源。

最后一点,非常重要的一点......每当您有一个接受指针的函数时,记录所有权语义就非常重要。它是调用者所拥有的吗?所有权是否转移? ETC。

In order to delete the pointers, you will need to store them somewhere. It is unclear where you do this (you don't have fields for all the pointer parameters accepted by the constructor), so I won't be able to give you exactly the code to do this, but I will lay out how you can go about doing this.....

To declare the destructor, add the following to your class declaration:

~cmysqldb();

Note that if your class will have any virtual methods, you should instead declare it as:

virtual ~cmysqldb();

And in your source file add:

cmysqldb::~cmysqldb()
{
    // contents of your destructor goes here.
}

Now, how exactly you free your resources depends on how they were allocated. If you used some library-specific create function and there is a library-specific free function, then use that. If it was allocated using malloc, then use free; if it was allocated with new, use delete; if it was allocated using new[], then use delete[]. Also, you should use smart pointer classes such as boost::scoped_ptr (std::unique_ptr) or boost::shared_ptr (std::shared_ptr), wherever possible to avoid explicitly managing these resources via new/delete in your constructors / destructors.

One last, very important point... whenever you have a function that accepts a pointer, it is very important that you document the ownership semantics. Is it owned by the caller? Is ownership transferred? Etc.

一笑百媚生 2024-11-15 02:47:50

当您使用 newnew[] & 获取动态内存时,就会发生内存泄漏。不要使用delete或delete[]`来释放内存。

您的构造函数声明属于以下类型:

cmysqldb(const char *text, MYSQL *connection, MYSQL_RES *result, 
         MYSQL_RES *fresult, MYSQL_FIELD *mfield);  

您应该使用 newnew[] 跟踪在构造函数中执行的任何动态内存分配,并且应该释放所有它们具有相应的deletedelete[]

A memory leak occurs when you acquire dynamic memory using new or new[] & do not deallocate the memory using delete or delete[]`.

Your constructor declaration is of the type:

cmysqldb(const char *text, MYSQL *connection, MYSQL_RES *result, 
         MYSQL_RES *fresult, MYSQL_FIELD *mfield);  

You should keep a track of whatever dynamic memory allocations you are doing in the constructor with new and new[]and you should deallocate all of them with a corresponding delete or delete[].

箜明 2024-11-15 02:47:50

最好的办法是使用智能指针来存储所有指向相关对象的指针。当父对象被销毁时,C++会自动调用所有子对象的析构函数。

如果您的父对象部分构造失败,则不会调用其析构函数。因此,如果您设计要在析构函数中释放的内容,则任何已分配的指针都会泄漏。但是,如果分配了子对象,则子对象析构函数就会运行,因此通过使用智能指针,可以为您处理部分分配的情况。

有关更多信息,请查找 RAII(资源获取即初始化)。

The best thing to do would be to use smart pointers to store all the pointers to related objects. C++ will automatically call destructors of all sub-objects when the parent object is destroyed.

And if your parent object fails partly constructed, its destructor won't be called. So any pointers already allocated would leak if you design things to be freed in the destructor. However, subobjects destructors get run if the subobject was allocated, so by using smart pointers this partly allocated case is taken care of for you.

For more information, look up RAII (Resource Acquisition Is Initialization).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文