Need to be removed from outside the indicator
-
Demonstration code:
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; // Первый запрос res = stmt->executeQuery("SELECT anything"); while (res->next()) { // перебор данных с запроса "SELECT anything" } delete res; // <----- Вопрос #1: Нужно ли делать delete res перед новым использованием переменной res? // Другой запрос res = stmt->executeQuery("SELECT another"); while (res->next()) { // перебор данных с запроса "SELECT another" } delete res; // <----- Вопрос #2: Достаточно ли сделать delete res только тут? return resultAnythngAndAnother;
}
- Question #1: Should we do
delete res
for new use
variableres
? - Question #2: Is that enough?
delete res
after
The last challenge (when it is no longer used)?
- Question #1: Should we do
-
The rule is that there is no simple rule of " do not think so " .
Every indicator in your program has owner - who is responsible for the life of the facility. It is the owner who must remove the object and must know when the object must be removed.
If you get an index from any function, in the documentation. obligation It's written whether you're given possession (and then you're now responsible for removing the object) or it's behind the previous owner (and you're not entitled to remove the object). If there's no such information in the documentation, you'll find out to the developer. If the developer is unavailable, try to use common sense.
If you're the one who develops the function that returns the index, You. You must decide whether or not to transfer possession of the object together with the index, and that fact is reflected in the documentation.
For your case, in terms of common sense, each.
stmt->executeQuery
distinguishes your own memory that doesn't belong to you, i.e., it reuses at every time.next()
♪ Probably, however, you must somehow close.Connection
Otherwise, the external code won't know when to release that memory.But actually, look at the documentation. Like these pages. http://dev.mysql.com/doc/connector-cpp/en/connector-cpp-examples-connecting.html ♪ http://dev.mysql.com/doc/connector-cpp/en/connector-cpp-examples-results.html Report:
Make sure that you free
con
, thesql::Connection
object, as soon as you do not need it any more. But do not explicitly freedriver
, the connector object.You must free the
sql::Statement
♪sql::Connection
, andsql::ResultSet
objects explicitly usingdelete
♪I mean, you're given possession (and responsibility for disposal)
con
♪stmt
♪res
but notdriver
♪Which means you have to remove the object by the index.
res
before you take it. variableres
new meaning (and lose the index to the object for which you are responsible).