jeudi 5 septembre 2019

How to push_back a unique_ptr in the vector of a derived class

I have an assignment to replicate the linux shell commands (ls, mkdir, etc) so I'm using a general tree structure. Basically, the directory class has a vector of pointers to either the base class (file) or another derived class (directory). Whenever I try to push_back a unique pointer to a new directory, I get the following error.

/usr/include/c++/8/ext/new_allocator.h:136:4: error: no matching function 
for call to ‘std::unique_ptr<FileData*>::unique_ptr(std::unique_ptr<Directory,
std::default_delete<Directory> >)’
 { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is my code

#include "FileData.h"
#include <vector>
#include <cctype>
#include <memory>

class Directory : public FileData
{
    private:
        Directory * parent;
        std::vector<std::unique_ptr<FileData*>> files;
        void eraseString(std::string & mainString, 
                const std::string & stringToErase);
        int amountOfChar(const std::string & check);
    public:
        Directory();
        Directory(Directory * par);
        ~Directory();
        Directory(const Directory & x);
        void listComputerFiles(std::string input);
        void changeDirectory(std::string input);
        void makeDirectory(std::string input);
        void removeDirectory(std::string input);
        void makeFile(std::string input);
        void removeFile(std::string input);
        void printCurrentDirectory();
};

class FileData
{
    friend class Directory;
    protected:
        std::string name;
        std::string restrictions;
        std::string timestamp;
        std::string owner;
        std::string group;
        int dataSize;
        int numberOfItems;
    public:
        FileData();
        FileData(std::string nameOfFile, std::string restrict, std::string time, 
            std::string own, int size, int itemNumber);
        virtual ~FileData();
};

And here is where the error happens

files.emplace_back(std::make_unique<Directory>(new Directory(*this)));

I tried many different combinations from other users having similars issues but to no avail including using a shared_ptr. As you can probably tell, I have no experience working with smart pointers, but felt like it was helpful to use them in this case due to having nested directories to clean up felt daunting.

Aucun commentaire:

Enregistrer un commentaire