How to copy dynamic object A* to list<A*>?

Hello, recently I tried to build OOP program using C++ (and Qt) but I got an problem right now.
Idea is: in function called foo() in main.cpp I need to get paths to all files into this directory, parse it and add to one pool that contains all parsed files from this directory.

It looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void foo()
{
  PathsRetriever* pr = new PathsRetriever("path_to_directory");
  Pool* p = new Pool(1) // pool id is 1

  for(int i = 0; i < pr->getPathsContainer().size(); i++)
  {
     do sth ...
     Log* l = new Log(1, file_path, words_count); // 1 - id, path, words count
     // here I need to add this Log to Pool and delete l after append to Pool
    
     delete l;
  }

  //here should I have acces to all elements of p, do sth with them and after   all release memory ofc;)

delete p;
}


Log has fields: 2 x unsigned, const string, 2 x map<string, unsigned>
Pool has fields: list<Log*>, unsigned (id)

I try to write a method in Pool class like below:

1
2
3
4
5
6
7
8
9
10
11
12
13
void Pool::Pool addToPool(Log* l)
{
  Log* temp = new Log();
  this->container.append(temp);
  this->pool.last() = log;
  delete temp;
}

but the result was not satisfacted - program has crashed.
Would anyone give me a tip how could I resolve this problem? Or maybe should I use non-dynamic object instead of pointers?

I'll be very glad for all replies.
Greetings. 
Last edited on
If you delete the object after you add it to the container, you're effectively adding a bad pointer to the list (the object it points no longer exists).

You should not delete the object as soon as it is added. Rather, you should delete the object when the pool/container is no longer using it.
Last edited on
That was it, thanks a lot!
Rather, you should not delete anything at all.
Bjarne Stroustrup wrote:
Code that creates an object using new and then deletes it at the end of the same scope is ugly, error-prone, and inefficient.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void foo()
{
  PathsRetriever pr("path_to_directory");
  Pool p(1); // pool id is 1

  for(int i = 0; i < pr.getPathsContainer().size(); i++)
  {
     do sth ...
     p.addToPool( Log(1, file_path, words_count) );
  }

  //here should I have acces to all elements of p, do sth with them and after   all release memory ofc;)
}

void Pool::Pool addToPool(const Log &log)
{
  this->container.append(log);
}
Topic archived. No new replies allowed.