RAII and assignment

I created the following class to connect sqlite3:

class SqliteConnection
{
public:
    sqlite3* native;

    SqliteConnection (std::string path){
        sqlite3_open_v2 (path.c_str(), &native, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
    }

    ~SqliteConnection (){
        sqlite3_close(native);
    }
}

and then you can initialize the connection as follows:

SqliteConnection conn("./database.db");

However, I would like to be able to use this connection, store it as a member in classes, etc., and the problem is with the default assignment operator operator=. Doing something like

SqliteConnection conn("./database.db");
SqliteConnection conn1 = conn;

will result in two sqlite3_close calls in the database pointer, as each variable is out of scope. How do you overcome this problem with RAII when you need to assign your resource to another variable?

+3
source share
3 answers

, , . . boost::shared_ptr :

class SqliteConnection {
    boost::shared_ptr<sqlite3> native;
public:
    SqliteConnection(const std::string& path) 
      : native(init_connection(path), &destroy_connection)
    {}
    // ...
};

sqlite3* init_connection(const std::string& path) {
    // ...
    return ptr;
}

void destroy_connection(sqlite3* p) {
    sqlite3_close(p);
}
+9

shared_ptr. , , - "shared_ptr" (). , boost ++ 0x.

+3

:

  • , , shared_ptr. , .
  • . SQLite. . .
  • Let the appropriation "steal" the resource. This is what it does auto_ptr. a = bleads to the fact that it areceives ownership of the bconnection, and is bset to zero, as an empty unused object.
  • Create a new connection when creating the copy. It depends on the sqlite API providing the required functionality. In particular, you may have to copy requests and other data related to the connection, which may be impractical.
0
source

Source: https://habr.com/ru/post/1755160/


All Articles