当我使用 boost 构建绝对路径时,无限递归

Infinite recursion when I build an absolute path using boost

本文关键字:路径 无限 递归 boost 构建      更新时间:2023-10-16

我需要一个函数来获取绝对路径,为此我查看了 boost,但它仅在最新版本中具有,并且我使用的是旧的 1.44。由于我无法在最近的 boost 1.55 或更高版本上更新我的代码,我决定重写该函数。它在 Windows 上运行良好,但我在 Linux 下陷入无限递归,我不明白为什么?该代码基于您可以在此处找到的描述

欢迎所有解决此问题的建议!谢谢

#include "boost/filesystem.hpp"
namespace bfs = boost::filesystem;
inline bfs::path absolute(const bfs::path& p, const bfs::path& base=bfs::current_path())
{
  if(p.has_root_directory())
  {
    if(p.has_root_name()) return p;
    else return absolute(base).root_name() / p;
  }
  else
  {
    if(p.has_root_name()) return bfs::path(p.root_name()) / bfs::path(absolute(base).root_directory()) / absolute(base).relative_path() / p.relative_path();
    else return absolute(base) / p;
  }  
}
最后,

我使用了 boost v1.55 代码的副本来解决这个问题。

inline bool is_absolute(const bfs::path p) 
{
#if defined(WIN32) || defined(WIN64)
  return p.has_root_name() && p.has_root_directory();
#else
  return p.has_root_directory();
#endif
}
inline bfs::path absolute(const bfs::path& p, const bfs::path& base=bfs::current_path())
{
  //  recursively calling absolute is sub-optimal, but is sure and simple
  bfs::path abs_base(is_absolute(base) ? base : absolute(base));
  //  store expensive to compute values that are needed multiple times
  bfs::path p_root_name (p.root_name());
  bfs::path base_root_name (abs_base.root_name());
  bfs::path p_root_directory (p.root_directory());
  if (p.empty()) 
  {
    return abs_base;
  }
  if (!p_root_name.empty())  // p.has_root_name()
  {
    if (p_root_directory.empty())  // !p.has_root_directory()
      return p_root_name / abs_base.root_directory()
      / abs_base.relative_path() / p.relative_path();
    // p is absolute, so fall through to return p at end of block
  } 
  else if (!p_root_directory.empty())  // p.has_root_directory()
  {
    return base_root_name / p;
  }
  else
  {
    return abs_base / p;
  }
  return p;  // p.is_absolute() is true
}