简体   繁体   中英

Using smart pointers with MySQL Connector

Most tutorials related to the mysql connector libraries assume, that the user will use raw pointers. I'd like to use smart pointers instead. I've written the following class:

class Database{
    private:
        bool _connected = false;
        std::shared_ptr<sql::Driver> _driver;
        std::shared_ptr<sql::Connection> _connection;
        std::shared_ptr<sql::Statement> _statement;
        std::shared_ptr<sql::ResultSet> _resource;
    public:
        Database();
        ~Database();
        bool connect(const std::string &ip, const std::string &user, const std::string password);
        bool connected();
};

I'm trying to implement the connect function, but I receive the following error during compilation:

/usr/include/c++/5.3.0/ext/new_allocator.h:120:4: error: invalid new-expression of abstract class type ‘sql::Driver’
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

It is caused by the following line of code:

this->_driver = std::make_shared<sql::Driver>(get_driver_instance());

What am I doing wrong? I've found few examples with smart pointers, but in every single one of them the sql::Driver instance is a raw pointer. Is it impossible to assign a result of the get_driver_instance() function to a smart pointer?

Update :

I think I should use the reset function instead of the make_shared template. Unfortunately this:

this->_driver.reset(get_driver_instance());

didn't solve the problem, I got this error:

/usr/include/cppconn/driver.h:39:10: error: ‘virtual sql::Driver::~Driver()’ is protected
virtual ~Driver() {}

I guess that the shared_ptr is unable to "claim" the Driver's destructor, because it's protected (as said in the error). Is there any workaround? Or maybe I should simply use a raw pointer when dealing with the sql::Driver ?

The resulting driver object pointer from get_driver_instance() is pointer to static storage object AFAIK and that pointer may not be delete d. So you do not need a smart pointer for managing its life time. Static objects are destroyed when program ends. Other objects in your post ( sql::Connection , sql::Statement , sql::ResultSet ) need to be deleted so you can use smart pointer for managing those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM