C++智能指针混乱

Ama*_*ani 3 c++ sqlite smart-pointers c++11

据我所知,在C++领域,它主张使用智能指针.我有一个简单的程序如下.

/* main.cpp */
#include <iostream>
#include <memory>
using namespace std;

/* SQLite */
#include "sqlite3.h"

int main(int argc, char** argv)
{
    // unique_ptr<sqlite3> db = nullptr; // Got error with this
    shared_ptr<sqlite3> db = nullptr;

    cout << "Database" << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我使用unique_ptr行编译时得到一条错误消息:

error C2027: use of undefined type 'sqlite3'
 error C2338: can't delete an incomplete type
Run Code Online (Sandbox Code Playgroud)

当我使用shared_ptr行编译时,它是成功的.从几个问题和答案我的理解是unique_ptr应该是首选,因为我不打算让对象共享资源.在这种情况下,最佳解决方案是什么?使用shared_ptr还是回到裸指针(new/delete)的旧方法?

Sto*_*ica 5

一般的方法是@ SomeProgrammerDudes的答案(接受它).但为了解决你的担忧,我发布了这个.

你不应该回到raw new并删除.既不是因为sqlite3是不透明的类型,也不是因为它的开销std::shared_ptr.您使用,作为指定的另一个答案,a std::unique_tr.

唯一的区别是您如何设置自定义删除器.因为std::unique_ptr它是类型定义的一部分,而不是运行时参数.所以你需要做这样的事情:

struct sqlite3_deleter {
  void operator()(sqlite3* sql) {
    sqlite3_close_v2(sql);
  }
};

using unique_sqlite3 = std::unique_ptr<sqlite3, sqlite3_deleter>;
Run Code Online (Sandbox Code Playgroud)