c++ - libpq 错误消息释放

标签 c++ libpq

这里有一个愚蠢的问题。 libpqPQerrorMessage 函数返回一个 char const*

char const* msg = PQerrorMessage(conn);

现在,由于它是 const,我认为我不应该释放它,而且我从未在任何示例中看到过这样做。但是,它何时以及如何被释放呢? 它怎么知道我何时使用完 msg 指针?

起初我以为一旦请求另一个错误消息,它就会被释放,但事实并非如此。

// cause some error
char const* msg1 = PQerrorMessage(pgconn);

// cause another error
char const* msg2 = PQerrorMessage(pgconn);

// still works
std::cout << msg1 << msg2 << std::endl;

有人可以帮我解释一下吗?

编辑:归功于 Dmitriy Igrishin

我在 postgresql 邮件列表上 asked 了这个,结果证明我最初的假设是正确的。
msg1 指针不应该有效,但我很幸运。

编辑:来自 postgresql 文档

PQerrorMessage

Returns the error message most recently generated by an operation on the connection.

char *PQerrorMessage(const PGconn *conn);

Nearly all libpq functions will set a message for PQerrorMessage if they fail. Note that by libpq convention, a nonempty PQerrorMessage result can consist of multiple lines, and will include a trailing newline. The caller should not free the result directly. It will be freed when the associated PGconn handle is passed to PQfinish. The result string should not be expected to remain the same across operations on the PGconn structure.

最佳答案

按照文档所说,不要期望它的内容保持不变,只需将它们保存在 std::string 中,而不是存储指针。

// cause some error
std::string msg1 = PQerrorMessage(pgconn);

// cause another error
std::string msg2 = PQerrorMessage(pgconn);

// works all the time
std::cout << msg1 << msg2 << std::endl;

关于c++ - libpq 错误消息释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13708993/

相关文章:

c++虚拟方法未被调用

c - 将 C 变量传递给 SQL 命令

postgresql - libpq,带参数插入

postgresql - PQescapeLiteral 未定义?

c++ - Qt,Designer 在 scrollArea 中创建 scrollAreaWidgetContents,但我无法调整图像标签的大小

c++ - 计算多个整数的位...有更快的方法吗?

c++ - boost::program_options bool_switch 使用多次

c++ - 使用 pqexecparams 通过 libpq 插入点

c - 使用 libpq 库将图像发送到 postgresql 数据库中的 bytea 列时出错

c++ - 如何从CGAL中的Linear_cell_complex_for_combinatorial_map中提取面部信息?