fork download
  1. #include <thread>
  2. #include <iostream>
  3.  
  4. class cl1;
  5. class cl2;
  6.  
  7.  
  8. class cl2 {
  9. public:
  10. int y;
  11. cl2(int y) : y(y) {} //ctor
  12. };
  13.  
  14. class cl1 {
  15. public:
  16. int x;
  17. cl1(int x) : x(x) {} //ctor
  18. cl1(cl2& ob1) : x(ob1.y * 2) {} //ctor for automatic conversion of cl2& to cl1, x = y*2
  19. };
  20.  
  21. void do_work_with_cl(cl1 ob) { //This works as usual by actually copying the object through the copy constructor
  22. std::cout << "The x of ob is " << ob.x << std::endl;
  23. }
  24.  
  25. void do_work_with_cl_rref(cl1&& ob) { //I guess this works because it takes an rvalue and the automatic
  26. //conversion ctor of cl1 does just that
  27. std::cout <<"Inside the function that takes cl1 as rvalue, x of ob is" << ob.x << std::endl;
  28. }
  29.  
  30. void do_work_with_cl_lref(cl1& ob) { //This doesn't work as ob is non-const lvalue reference
  31. std::cout << "lvalue referenced but the object created through implicit conversion is temporary(i.e rvalue)" << std::endl;
  32. }
  33.  
  34.  
  35. int main() {
  36. //Normal non-threaded calls
  37. cl2 ob(100); //create a cl2 object
  38. do_work_with_cl(ob); //This is ok
  39. do_work_with_cl_rref(ob); //This too works
  40. //do_work_with_cl_lref(ob) //This fails, as suspected
  41.  
  42. std::cout << "Thread part" << std::endl;
  43.  
  44. //Now calling the functions through a thread
  45. std::thread t1(do_work_with_cl_rref, ob); //Thought this could work here, but doesn't
  46. //The other functions also don't work, but I can understand why.
  47. t1.join();
  48. }
  49.  
Success #stdin #stdout 0s 11224KB
stdin
Standard input is empty
stdout
The x of ob is 200
Inside the function that takes cl1 as rvalue, x of ob is200
Thread part
Inside the function that takes cl1 as rvalue, x of ob is200