简体   繁体   English

在MySQL Connector中使用智能指针

[英]Using smart pointers with MySQL Connector

Most tutorials related to the mysql connector libraries assume, that the user will use raw pointers. 大多数与mysql连接器库相关的教程都假定用户将使用原始指针。 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: 我正在尝试实现connect函数,但是在编译过程中收到以下错误:

/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. 我发现了几个带有智能指针的示例,但是在其中每个示例中, sql::Driver实例都是原始指针。 Is it impossible to assign a result of the get_driver_instance() function to a smart pointer? 不可能将get_driver_instance()函数的结果分配给智能指针吗?

Update : 更新

I think I should use the reset function instead of the make_shared template. 我想我应该使用reset函数而不是make_shared模板。 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). 我猜想shared_ptr无法“声明”驱动程序的析构函数,因为它是受保护的(如错误中所述)。 Is there any workaround? 有什么解决方法吗? Or maybe I should simply use a raw pointer when dealing with the sql::Driver ? 或者也许我应该在处理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. get_driver_instance()得到的驱动程序对象指针是指向静态存储对象AFAIK的指针,并且该指针可能不会被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. 需要删除帖子中的其他对象( sql::Connectionsql::Statementsql::ResultSet ),以便可以使用智能指针来管理这些对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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