I have a simple filesystem containing either a file or a directory. I have created an abstract class as a parent of both of these classes + two functions Size() and Change() as can be seen here:
class AbstractParent {
public:
explicit AbstractParent (const string & name = "", const unsigned int size = 0) : cString(name), cSize(size) {};
virtual ~AbstractParent() = default;
virtual unsigned int Size() const = 0;
unique_ptr<AbstractParent> Clone() const {
unique_ptr<AbstractParent> other(this->deepClone());
return other;
}
protected:
string cString;
unsigned int cSize;
//virtual copy constructor
virtual AbstractParent * deepClone() const = 0;
};
class CFile : public AbstractParent
{
public:
// constructor
explicit CFile (const string & hash, const unsigned int size) : AbstractParent(hash,size) {};
// Size
unsigned int Size() const override{
return cSize;
}
// Change
CFile & Change (const string & newHash, const unsigned int newSize) {
cString = newHash;
cSize = newSize;
return *this;
}
//virtual copy constructor
CFile * deepClone () const override{
return new CFile(*this);
}
};
class CDirectory : public AbstractParent
{
public:
// constructor
explicit CDirectory () {
systemMap = new map<string, unique_ptr<IFileSystem>>; //valgrind reports a leak here
};
// Size
unsigned int Size () const override {
return cSize;
}
// Change
CDirectory & Change (const string & FSName,const IFileSystem & file) {
systemMap->insert(make_pair(FSName, file.Clone()));
return *this;
}
//virtual copy
CDirectory * deepClone () const override {
return new CDirectory(*this);
}
private:
map<string, unique_ptr<IFileSystem>> * systemMap;
};
I have a problem with insering a directory into another directory. I would like to use a map for the directory, where the key is the name of the file/directory and its value is a pointer to the instance of it.
Here I have attempted to make it function with a virtual copy constructor and while it does compile, it does not work properly. Valgrind is reporting lost memory where I allocate new map.
code in main to test out my implementation:
int main ()
{
CDirectory root;
stringstream sout;
root.Change("file.txt", CFile("jhwadkhawkdhajwdhawhdaw=", 1623))
.Change("folder", CDirectory()
.Change("fileA.txt", CFile("", 0).Change("skjdajdakljdljadkjwaljdlaw=", 1713))
.Change("fileB.txt", CFile("kadwjkwajdwhoiwhduqwdqwuhd=", 71313))
.Change("fileC.txt", CFile("aihdqhdqudqdiuwqhdquwdqhdi=", 8193))
);
return 0;
}
While debugging, everything gets inserted into the map of root as intended.
Only problem that remains is the memory of the map is lost. Where should I free this memory, if it does not get freed implicitly?