1

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?

1 Answer 1

1

The resulting driver object pointer from get_driver_instance() is pointer to static storage object AFAIK and that pointer may not be deleted. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I didn't notice that indeed no one is deleting the driver pointer in their examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.