Search code examples
c++classpointersconstructorraii

What's the proper way to handle an RAII member variable?


I'm new to C++ and don't yet fully understand the RAII pattern. I'm writing a class which uses an sqlite database via SQLiteC++. Here is some sample code that uses the database that works:

void test() {
    SQLite::Database db(TestDbPath(), SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);

    db.exec("DROP TABLE IF EXISTS test");
    db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, foobar TEXT)");
}

What I want to do is use an SQLite::Database from a class. Something like this would work:

class DBUser
{
private:
    SQLite::Database *db;

public:
    explicit DBUser(std::string &path) {
        db = new SQLite::Database(path, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
    }
    ~DBUser() {
        delete db;
    }

    void test() {
        db->exec("DROP TABLE IF EXISTS test");
        db->exec("CREATE TABLE test (id INTEGER PRIMARY KEY, foobar TEXT)");
    }
}

Is that the best way, though? Is there a more idiomatic/elegant way to accomplish this without a pointer?


Solution

  • Just have an object as a member:

    class DBUser
    {
    private:
        SQLite::Database db;
    
    public:
        explicit DBUser(std::string &path) :
            db (path, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE) 
        {
    
        }
        void test() {
            db.exec("DROP TABLE IF EXISTS test");
            db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, foobar TEXT)");
        }
    }