Subject: libpq usage from C++

From: Igor Korot <[email-masked]>
Date: Fri, 13 Mar 2026 23:40:48 -0500

Hi, ALL,

Does anybody use libpq from C++?

C++ introduces STL.
C++ introduces smart-pointers.

Is there a simple way of using those writing libpq communication?

Or should I just forget about them and use good old "dump pointers"?

Thank you.

---

From: Adrian Klaver <[email-masked]>
Date: Fri, 13 Mar 2026 21:51:29 -0700

> Does anybody use libpq from C++?

Search engine of choice:

libpq c++

yields:

https://pqxx.org/development/libpqxx/

-- 
Adrian Klaver
[email-masked]

---

From: Dominique Devienne <[email-masked]>
Date: Mon, 16 Mar 2026 11:25:15 +0100

> Does anybody use libpq from C++?

Yes

> Or should I just forget about them and use good old "dump pointers"?

Using an existing wrapper is simplest, of course.
We wrote our own. To each its own. E.g.

PS: Avoid the fwd-decl by using the actual libpq headers instead.

extern "C" {

struct pg_conn;
struct pg_result;
typedef struct pg_conn PGconn;
typedef struct pg_result PGresult;
typedef struct _PQconninfoOption PQconninfoOption;
typedef struct pgNotify PGnotify;
void PQfreemem(void *ptr);
void PQclear(PGresult* res);
void PQfinish(PGconn* conn);
void PQconninfoFree(PQconninfoOption* conn);

} // extern "C"

namespace acme::postgresql {

struct PGDeleterFunctor {
    void operator()(PGresult* r) {
        if (r != nullptr) {
            PQclear(r);
        }
    }
    void operator()(PGconn* c) {
        if (c != nullptr) {
            PQfinish(c);
        }
    }
    void operator()(PQconninfoOption* c) {
        if (c != nullptr) {
            PQconninfoFree(c);
        }
    }
    void operator()(PGnotify* n) {
        if (n != nullptr) {
            PQfreemem(n);
        }
    }
};
using PGresult_uptr     = std::unique_ptr<PGresult,         PGDeleterFunctor>;
using PGconn_uptr       = std::unique_ptr<PGconn,           PGDeleterFunctor>;
using PGconninfo_uptr   = std::unique_ptr<PQconninfoOption, PGDeleterFunctor>;
using PGnotify_uptr     = std::unique_ptr<PGnotify,         PGDeleterFunctor>;

...
}

Then we have higher-level wrappers that compose those RAII low-level ones. --DD