vendredi 24 septembre 2021

Best practices for passing 'this' to class with smart pointers [closed]

I have a file in a certain format, which represents a file system. In addition, I have a class called 'FS', which parsing the above file, and builds an array of files. It looks like this:

class File
{
    friend FS;

private:
    FS * fs;

public:
    File(FS *fs) : fs(fs) {
        ...
    }
    
    void readFile() {
        fs->readSector(...);
    }
}

class FS
{
    private:
        std::vector<File> files;
    
        int readSector(...) {
            ...
        }
    
        void parse() {
            for (...) {
                readSector(...);
            }
        }
        
    public:
        File getFileByName(...) {
            return File(this);
        }
}
  1. What's the best way to pass 'this' to the 'File' class?
  2. Should I use smart pointers? If so, how should I use them in this case? If I did use them, what would happen if I make an instance of 'FS' with a 'new' operator but inside I would use with smart pointers for 'this'?
  3. Is the use of 'friend' right here?

Aucun commentaire:

Enregistrer un commentaire