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

时间:2013-03-04 01:23:16

标签: c++ map destructor friend unique-ptr

我有这样的安排:

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

class Lex
    {
//...
private:
    std::map<std::string, std::unique_ptr<LexedFile> > Files;
    };

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

我的问题是:我的便携式选项是什么让unique_ptr感到高兴并且仍然保持~LexedFile()私密?通过便携式,我想它必须至少使用最新的g ++和最新的Visual C ++。

我插入了类似的内容:

friend class std::unique_ptr<LexedFile>;

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

1 个答案:

答案 0 :(得分:4)

使用您自己的删除器实例化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;
};
相关问题