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