5

Using this code, I got and error :

Error 1 error C2064: term does not evaluate to a function taking 1 arguments c:\program files (x86)\microsoft visual studio 11.0\vc\include\functional 1152 1 Pipeline

class PipelineJob { private: std::thread *thread; void execute(PipelineJob* object); public: void execute(PipelineJob* object) { } PipelineJob() { this->thread = new std::thread(&PipelineJob::execute, this); } }; 

I tried many variation, any one now how to solve this?

6
  • 4
    The design with pointers and new is silly and terrible. You should use a constructor initializer list. Commented May 23, 2013 at 16:03
  • 2
    Also, your code makes no sense. Is PipelineJob a class or a template? Commented May 23, 2013 at 16:05
  • hmm, I tried with initialization list, but I was still getting an error of build because I was trying to access the default constructor which doesn't exist. Commented May 23, 2013 at 16:05
  • I removed all code not useful for the problem. Commented May 23, 2013 at 16:05
  • possible duplicate of Start thread with member function Commented May 23, 2013 at 18:31

1 Answer 1

17

Removing the templates and the pointers for simplicity, this is more or less what you would want:

class PipelineJob { private: std::thread thread_; void execute(PipelineJob* object) { ..... } public: PipelineJob() { thread_ = std::thread(&PipelineJob::execute, this, this); } ~PipelineJob() { thread_.join(); } }; 

Note that this is passed two times to the std::thread constructor: once for the member function's implicit first parameter, the second for the visible parameter PipelineJob* object of the member function.

If your execute member function does not need an external PipelineJob pointer, then you would need something like

class PipelineJob { private: std::thread thread_; void execute() { ..... } public: PipelineJob() { thread_ = std::thread(&PipelineJob::execute, this); } ~PipelineJob() { thread_.join(); } }; 
Sign up to request clarification or add additional context in comments.

5 Comments

And what's the point of passing this twice? I think the OP just misunderstood what member functions are...
Nope, I know what's a member function ;). We don't need "this" twice. when using a static function you don't need to give this reference. But with a none-static it is needed. That way in the function you can use directly this keyword. So you should remove from execute function the parameter since we can access this.
@pikaille correct. But if you could call execute with different PipelineJob instances. In this example I use this twice, but it doesn't have to be like that. You could have pointers to two different PipelineJob instances.
@Yakk some concern about the object not being fully constructed when the thread starts. I don't know what execute does with this. Probably just being over cautious.
@juanchopanza Yes there could be a use case, in mine I just needed the this reference, so the second this becomes useless.