本文介绍了C ++ unique_ptr与friend类的私有析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的安排:

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() public来解决这个问题,但是,当然,我把它私密的原因是强化该类型的对象只属于 Lex 对象。

A Lex is the sole creator of LexedFile objects and retains ownership of all the LexedFile objects it creates in a map. Unfortunately, the compiler complains mightily about this due to visibility rules from the map variable to the LexedFile destructor. I can fix that problem by making ~LexedFile() public, but of course the reason I made it private is to reinforce the decision that objects of that type belong only to Lex objects.

我的问题是:我的便携式选项是 unique_ptr 快乐,仍然保持〜LexedFile()私人?通过便携式,我想它必须至少使用最新的g ++和最新的Visual C ++。

My question is: what are my portable options for making unique_ptr happy and still keeping ~LexedFile() private? By portable, I guess it has to at least work with the latest g++ and the latest Visual C++.

我插入一些东西,如:

friend class std::unique_ptr<LexedFile>;

但是即使它已经工作了(它没有),它似乎依赖于关于

but even if it had worked (it didn't) it kinda seemed like relying on assumptions about the implementation that might not be portable.

推荐答案

只需实例化 std :: unique_ptr 用你自己的删除程序。我认为这将工作:

Just instantiate std::unique_ptr with your own deleter. I think this will work:

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;
};

这篇关于C ++ unique_ptr与friend类的私有析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 11:14