RAII 和分配
我为 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);
}
}
然后可以按如下方式初始化连接
SqliteConnection conn("./database.db");
但是,我希望能够共享此连接,将其存储为类中的成员等,问题在于默认值赋值运算符operator=
。 执行类似的操作
SqliteConnection conn("./database.db");
SqliteConnection conn1 = conn;
当每个变量超出范围时, 会导致对数据库指针进行两次 sqlite3_close 调用。当您需要将资源分配给不同的变量时,如何使用 RAII 克服这一困难?
I created the following class for an sqlite3 connection:
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 one can initialize a connection as follows
SqliteConnection conn("./database.db");
However, I would like to be able to share this connection, store it as a member in classes, etc., and the trouble is with the default assignment operator operator=
. Doing something like
SqliteConnection conn("./database.db");
SqliteConnection conn1 = conn;
would lead to two sqlite3_close calls on the database pointer as each variable goes out of scope. How do you overcome this difficulty with RAII when you need to assign your resource to a different variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于共享资源,您必须跟踪对它们的引用是否存在,例如使用引用计数 。一种实现是
boost::shared_ptr
使用自定义删除器:For shared resources you will have to keep track of wether references to them exist, e.g. using reference counting. One implementation is
boost::shared_ptr
with a custom deleter:将连接放入shared_ptr 中。在分配时,您所要做的就是分配“shared_ptr”以拥有资源(连接)的共享所有权。否则,您必须为您的类实现共享所有权,这已经在 boost 中完成并包含在 C++0x 中。
Put the connection in a shared_ptr. On assignment all what you have to do is to assign "shared_ptr"s to have shared ownership of the resource(connection). Otherwise you have to implement shared ownership for your class which already has been done in boost and is included in C++0x.
您有四个基本选项:
shared_ptr
。这是效率最低的,但却是最通用的解决方案。auto_ptr
的作用。a = b
导致a
取得b
连接的所有权,并将b
设置为空值,作为一个空的、无法使用的对象。You have four basic options:
shared_ptr
. This is the least efficient, but it's the most general solution.auto_ptr
does.a = b
results ina
taking ownership ofb
's connection, andb
being set to a null value, as an empty, unusable object.