C++删除运算符.如何正确使用
C++ delete operator. How to use properly?
请帮助新手进行运算符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 res
当res
不是应该delete
的指针时,d比什么都不做更有可能产生不需要的效果。
对于第二个,如果(并且仅当(您需要delete res
,只做一次。 删除指针两次会产生未定义的行为。
简而言之:只有在你知道需要时才delete res
,不要delete res
多次。
-
是的。
-
对于每个新内容,必须删除一次,否则将出现内存泄漏。您只需在使用完分配的任何内容后删除一次。
另一个好的编程实践是做
res = nullptr;
所以你不会有任何悬空的指针。但是在这个特定的代码段中不需要这样做
您还应该阅读有关智能指针的信息,根据bjarne stroustrup,在现代C ++中不应使用new和delete。
除非您分配了new
或您正在调用的函数的文档说客户端必须使用 delete
释放内存,否则您不应该在该指针上盲目调用delete
。
你不知道那个指针是从哪里来的。 它可以是用new
创建的,也可以是用malloc
创建的,它可能是更大的内存池中的指针,你不知道。
通常情况下,文档会声明调用其他一些函数来释放内存或句柄。
- 如何正确删除这些指针?
- 从 QAbstractItemModel 中正确删除子树
- 正确删除с++中的类
- 何时/如何在使用指针后正确删除指针?
- 如何正确删除 std::string 数组
- 如何在单链列表 c++ 中正确删除节点
- 如何正确删除具有已知二维大小的二维数组
- C :如何正确删除在类破坏者中的指针
- 如何正确删除一行控件并在该位置动态创建一个新控件
- 我是否正确删除了指向对象的指针向量?
- 如何在C 中正确删除树
- 使用抽象类时,如何正确删除指针
- BST 节点删除 - 指针未正确删除
- C++应用程序:如何正确删除/释放已分配的对象
- 如何从动态内存中正确删除对象的指针
- C 正确删除动态分配的内存
- 如何正确删除是中央小部件的Qgraphicsview对象
- 如何在C++中正确删除链表的节点
- 正确删除向量的元素
- 正确删除EGL Opengles 2.0