Poco::Path 使用 const wchar_t* 编译但行为异常

Poco::Path compiles with const wchar_t* but behaves unexpectedly

使用 Poco::Path 我发现了一个非常奇怪的错误。见以下代码:

#include <iostream>
#include <string>
#include <Poco/Path.h>

int main()
{
  std::wstring a_path = L"c:\temp";

  //Poco::Path from_wstring(a_path); // ERROR: fails to compile, expected
  Poco::Path from_wchar_t(a_path.c_str()); // compiles... unexpected

  std::cout << from_wchar_t.toString() << std::endl;

  return 0;
}

但是上面程序的输出是(在Windows):

\

而不是预期的:

c:\temp

查看 Poco::Path 文档,我没有看到构造函数期望 std::wstring(这就是第一条路径失败的原因)也没有 const wchar_t*,仅来自 std::stringconst char*(均为 UTF-8)。

如何使用 const wchar_t* 编译以及为什么会出现意外输出(错误路径)?

在为这个问题创建 mvce 时,我发现了问题所在。我决定在这里记录它以防它对其他人有帮助。

问题中显示的代码片段是一个巨大项目的一部分,所以我错过了一个编译警告:

warning C4800: 'const wchar_t *' : forcing value to bool 'true' or 'false' (performance warning)

然后我意识到有一个构造函数 Poco::Path::Path(bool absolute) 并且编译器自动将指针转换为 bool,然后产生了意想不到的行为。输出的\对应一个空的绝对路径,它在使用这种构造函数时的初始值。


对于那些对解决方法感兴趣的人,我现在正在使用 UTF-16 到 UTF-8 的转换:

#include <boost/locale/encoding.hpp>
// ...
std::wstring a_path = L"c:\temp";
Poco::Path utf8_path(boost::locale::conv::utf_to_utf<char>(a_path));