C++ unique_ptr versus friend class private destructor

谁都会走 提交于 2019-12-10 20:10:44

问题


I have this arrangement:

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

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

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.

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++.

I took a stab at inserting something like:

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.


回答1:


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


来源:https://stackoverflow.com/questions/15193108/c-unique-ptr-versus-friend-class-private-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!