fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. class A
  5. {
  6. public:
  7. std::vector<int> data;
  8.  
  9. A () = default;
  10. explicit A(const A&) = default; // <---- accidental copies are avoided
  11.  
  12. void DoTheThing()
  13. {
  14. while (data.size() < 10) {
  15. data.push_back(1);
  16. }
  17. }
  18. };
  19.  
  20. class B
  21. {
  22. public:
  23. std::vector<A> objs;
  24.  
  25. B()
  26. {
  27. A one, two, three;
  28. objs.push_back(one);
  29. objs.push_back(two);
  30. objs.push_back(three);
  31. }
  32.  
  33. void DoTheThing()
  34. {
  35. for (auto obj: objs) { // <---- error due to `explicit` copy consttructor
  36. obj.DoTheThing();
  37. std::cout << "DEBUG length during=" << obj.data.size() << std::endl;
  38. }
  39. }
  40. };
  41.  
  42. int main()
  43. {
  44. B b;
  45. b.DoTheThing();
  46. for (auto& obj : b.objs) { // <--- OK
  47. std::cout << "DEBUG length after=" << obj.data.size() << std::endl;
  48. }
  49.  
  50. return 0;
  51. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In member function 'void B::DoTheThing()':
prog.cpp:35:24: error: no matching function for call to 'A::A(A&)'
         for (auto obj: objs) {  // <---- error due to `explicit` copy consttructor
                        ^
prog.cpp:9:5: note: candidate: A::A()
     A () = default;
     ^
prog.cpp:9:5: note:   candidate expects 0 arguments, 1 provided
stdout
Standard output is empty