C++ unique_ptr 与友元类私有析构函数

Ron*_*urk 3 c++ dictionary destructor friend unique-ptr

我有这样的安排:

class LexedFile
    {
    friend class Lex;
//...
private:
    ~LexedFile();
    };

class Lex
    {
//...
private:
    std::map<std::string, std::unique_ptr<LexedFile> > Files;
    };
Run Code Online (Sandbox Code Playgroud)

Lex 是LexedFile对象的唯一创建者,并保留LexedFile其在映射中创建的所有对象的所有权。不幸的是,由于从映射变量到LexedFile析构函数的可见性规则,编译器强烈抱怨这一点。我可以通过公开来解决这个问题~LexedFile(),但是当然,我将其设为私有的原因是为了强化该类型的对象仅属于Lex对象的决定。

我的问题是:我有哪些便携式选项可以让我unique_ptr开心并保持~LexedFile()私密性?对于可移植性,我想它至少必须与最新的 g++ 和最新的 Visual C++ 一起工作。

我尝试插入类似的内容:

friend class std::unique_ptr<LexedFile>;
Run Code Online (Sandbox Code Playgroud)

但即使它有效(它没有),它似乎依赖于关于可能不可移植的实现的假设。

Ste*_*Lin 5

只需std::unique_ptr使用您自己的删除器实例化即可。我认为这会起作用:

class LexedFile
{
    friend class Lex;

//...
private:
    struct Deleter
    {
        void operator()(LexedFile *file) const
        {
            delete file;
        }
    };

    ~LexedFile();
};

class Lex
{
//...
private:
    std::map<std::string, std::unique_ptr<LexedFile, LexedFile::Deleter>> Files;
};
Run Code Online (Sandbox Code Playgroud)