这里有一个愚蠢的问题。 libpq
的 PQerrorMessage
函数返回一个 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 nonemptyPQerrorMessage
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 associatedPGconn
handle is passed toPQfinish
. The result string should not be expected to remain the same across operations on thePGconn
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/