C++删除运算符.如何正确使用

C++ delete operator. How to use properly?

本文关键字:何正确 删除 运算符 C++      更新时间:2023-10-16

请帮助新手进行运算符delete
演示代码:

MyType getDataFromDB()
{
    Driver *driver;
    Connection *con;
    Statement *stmt;
    ResultSet *res;
    /* Create a connection */
    driver = get_driver_instance();
    con = driver->connect("tcp://127.0.0.1:3306", "login", "pass");
    /* Connect to the MySQL test database */
    con->setSchema("schema");
    stmt = con->createStatement();
    MyType resultAnythngAndAnother;
    // First query
    res = stmt->executeQuery("SELECT anything");
    while (res->next())
    {
        // fetch data from "SELECT anything"
    }
    delete res; // <----- Question #1: Should I every time call delete res before next assigning of res variable?
    // Another query
    res = stmt->executeQuery("SELECT another");
    while (res->next())
    {
        // fetch data from "SELECT another"
    }
    delete res; // <----- Question #2: Is it enough to call delete res only once here? Since it won't be used anymore.
    return resultAnythngAndAnother;
}
  • 问题#1:我应该每次在下次分配res变量之前调用删除res吗?
  • 问题#2:只调用一次删除res就足够了吗?因为它不会再被使用。

谢谢。

你应该使用std::make_unique - 完全避免裸指针,除非你有特殊情况,你不负责释放对象。

对于第一个

res = stmt->executeQuery("SELECT anything");
while (res->next())
{
    // fetch data from "SELECT anything"
}
delete res; // <----- Question #1: Should I every time call delete res before next assigning of res variable?

答案取决于文档对影响res的功能的说明。 在这种情况下,答案归结为stmt->executeQuery()res->next()的行为。 虽然我预计res->next()的调用不会影响您是否需要发布res,但阅读文档是确定的唯一方法。

如果文档明确指出您需要在完成后delete res,那么您应该这样做。

如果它说你需要在完成后调用一些其他函数(比如Release(res)(,你应该这样做。

如果文档对此没有任何说明,则最好什么都不做。 当你不知道时,delete resres不是应该delete的指针时,d比什么都不做更有可能产生不需要的效果。

对于第二个,如果(并且仅当(您需要delete res,只做一次。 删除指针两次会产生未定义的行为。

简而言之:只有在你知道需要时才delete res,不要delete res多次。

  1. 是的。

  2. 对于每个新内容,必须删除一次,否则将出现内存泄漏。您只需在使用完分配的任何内容后删除一次。

另一个好的编程实践是做

res = nullptr;

所以你不会有任何悬空的指针。但是在这个特定的代码段中不需要这样做

您还应该阅读有关智能指针的信息,根据bjarne stroustrup,在现代C ++中不应使用new和delete。

除非您分配了new或您正在调用的函数的文档说客户端必须使用 delete 释放内存,否则您不应该在该指针上盲目调用delete

你不知道那个指针是从哪里来的。 它可以是用new创建的,也可以是用malloc创建的,它可能是更大的内存池中的指针,你不知道。

通常情况下,文档会声明调用其他一些函数来释放内存或句柄。