关于std :: unique_prt()和decltype()

问题描述 投票:0回答:1

std::unique_ptr<std::FILE, decltype(&close_file)> fp(std::fopen("demo.txt", "r"), &close_file);是什么意思?

我知道std::uqiue_ptr是唯一的指针。但是我无法理解整个表达。

有人能帮我一个忙吗?

  void close_file(std::FILE* fp) { std::fclose(fp); }

  std::cout << "Custom deleter demo\n";
  std::ofstream("demo.txt") << 'x'; // prepare the file to read
  {
      std::unique_ptr<std::FILE, decltype(&close_file)> fp(std::fopen("demo.txt", "r"),
                                                           &close_file);
      std::cout<<typeid((&close_file)).name()<<std::endl;
      if(fp) // fopen could have failed; in which case fp holds a null pointer
        std::cout << (char)std::fgetc(fp.get()) << '\n';
  }
c++ shared-ptr
1个回答
0
投票

给出void close_file(std::FILE* fp) { std::fclose(fp); }

[decltype(&close_file)void(*)(stdFILE*)(功能指针)。

您可以为std::unique提供自定义删除器,这是在这里完成的操作:

std::unique_ptr<std::FILE, decltype(&close_file)> fp(std::fopen("demo.txt", "r"),
                                                     &close_file);

尽管我认为最好有更好的删除器:

struct file_closer
{
    void operator()(std::FILE* fp) const { std::fclose(fp); }
};

甚至

template <auto* func>
using Functor = std::integral_constant<decltype(func), func>;

using file_closer = Functor<&std::fclose>;

用作

std::unique_ptr<std::FILE, file_closer> fp(std::fopen("demo.txt", "r"));

© www.soinside.com 2019 - 2024. All rights reserved.