I understand that in the C++ realm it is advocated to use smart pointers. I have a simple program as below.
/* main.cpp */
#include <iostream>
#include <memory>
using namespace std;
/* SQLite */
#include "sqlite3.h"
int main(int argc, char** argv)
{
// unique_ptr<sqlite3> db = nullptr; // Got error with this
shared_ptr<sqlite3> db = nullptr;
cout << "Database" << endl;
return 0;
}
When I compile with unique_ptr line got an error message:
error C2027: use of undefined type 'sqlite3'
error C2338: can't delete an incomplete type
When I compile with shared_ptr line it is successful. From several questions and answers my understanding is that unique_ptr should be preferred as I do not intended to have objects sharing resources. What is the best solution in this case? Use shared_ptr or go back to the old approach of bare pointers (new/delete)?
The general approach is in @SomeProgrammerDudes's answer (accept it). But to address your concerns I'm posting this.
You shouldn't go back to raw new and delete. Neither because sqlite3 is an opaque type nor because the overhead of std::shared_ptr. You use, as the other answer specified, a std::unique_tr.
The only difference is how you setup the custom deleter. For std::unique_ptr it's part of the type definition, not a run-time parameter. So you need to do something like this:
struct sqlite3_deleter {
void operator()(sqlite3* sql) {
sqlite3_close_v2(sql);
}
};
using unique_sqlite3 = std::unique_ptr<sqlite3, sqlite3_deleter>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With