1

I have the following piece of code:

void f(){
  .....
  std::vector<PrepareLogFileThread> v;

  for(int i = 0; i < list.length(); ++i){

    PrepareLogFileThread a(  
                list[i],
                LOG_TEMPLATE);
    a.start();
    v.push_back( a );
  }
  ....
}

class PrepareLogFileThread inherits from a Thread class that uses pthread (we use c++98 standard.... and I can use auto_ptr).

The problem here is that Thread's copy constructor is private so that is doesn't mess up the execution or something (I am not the author of this class).

The idea here is that I create my PrepareLogFileThread objects, push_back to v, start them and then they all finish before f returns.

PrepareLogFileThread has in destructor call to pthread_join so that it finishes there.

But I can't because I copy a in line with push_back.

How can I do it without c++11 and changing Thread's copy constructor?

I am using gcc 4.4.6 and I can use auto_ptr.

Patryk
  • 22,602
  • 44
  • 128
  • 244
  • 2
    You'd need your own container, which doesn't require copyable types and allows in-place construction ("emplacement") like the C++11 containers. Or possibly add a level of indirection and store pointers to dynamic objects (carefully deleting them as appropriate, since you don't have any suitable smart pointers). [Boost](http://www.boost.org/doc/libs/1_57_0/doc/html/container.html) might help, if you really are stuck in the past. – Mike Seymour Mar 04 '15 at 17:46

2 Answers2

1

You could store the pointer to the object.

std::vector<PrepareLogFileThread*> v;  

You should be careful about the lifetime of the object.

cppcoder
  • 22,227
  • 6
  • 56
  • 81
1

Standard containers assume their elements support value semantics (which includes, in your parlance, being "copyable" - among other things).

One option is to create a container of your own that does not require such semantics. That is difficult, for various reasons.

Alternatively, have your container elements be something else which that does have value semantics, where the value uniquely identifies an instance of your PrepareLogFileThread class. An obvious choice for such a "something" is a pointer. For example;

void f()
{
    std::vector<PrepareLogFileThread *> v;

    for(int i = 0; i < list.length(); ++i){

    PrepareLogFileThread *a = new PrepareLogFileThread(  
                list[i],
                LOG_TEMPLATE);
    a->start();
    v.push_back( a );
  }
}

Keep in mind, however, that it is necessary to delete the elements of the vector v before it ceases to exist - objects created with operator new are not automatically destroyed up when done. Failing to do this will result in a memory leak.

Note also that std::auto_ptr does not support value semantics, so should not be stored in a standard container.

Rob
  • 1,966
  • 9
  • 13