0

code snippet looks like: //main.cpp:

in main()
{
   Demo demo; //Instance for class Demo

   while(1)
   {
     std::mutex cv_m;
     std::unique_lock<std::mutex> lock(cv_m);
     std::chrono::seconds time_period(20);
     auto time_duration = std::chrono::system_clock::now() + time_period;

     //this is wrong, but just show what I want to do
     if(demo.cond_var.wait_util(lock, timeDuration, [demo, event_num](){return demo.getEventNum() == event_num; })){
       std::cout<<" Reach the points!"<<std::endl;
       break;
     }
    else{
       std::cout<<"Timed out!"<<std::endl;
       break;
    }


   }

}

The purpose is to keep checking the event number (which will be updated by other threads), if it reaches to 20, break from the loop or till it times out.

Above code failed to compile with error: use of deleted function Demo(const Demo&) So my question is if without copy ctor, is there a way to do what I want to do? I may not able to allow to add the copy ctor for the class.

Thanks.

issac
  • 155
  • 8
  • 1
    Capture `demo` by *reference* instead of by *value*? – NathanOliver May 12 '23 at 13:43
  • 3
    I dont want to discourage you, but I suggest you to go a bit slower. Read about the stuff you are using before using it. This time it was only a compiler error, next time it could be worse. Any introduction to lambdas should mention capture by reference. Perhaps all you are missing is a good [book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) or [c++ reference](https://en.cppreference.com/w/cpp/language/lambda) – 463035818_is_not_an_ai May 12 '23 at 13:49

0 Answers0