fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <stdexcept>
  4. using namespace std;
  5.  
  6. class S
  7. {
  8. private:
  9. int* data;
  10. bool is_const;
  11. public:
  12. S() : data(new int[10]), is_const(false) { data[1] = 42; }
  13. S(const S& other) : data(other.data), is_const(true) {}
  14. S(S& other) : data(other.data), is_const(false) {}
  15.  
  16. int& operator()(size_t i)
  17. {
  18. if (is_const)
  19. throw std::logic_error("non-const operation attempted");
  20. return data[i];
  21. }
  22.  
  23. const int& operator()(size_t i) const
  24. {
  25. return data[i];
  26. }
  27. };
  28.  
  29. int main() {
  30. try
  31. {
  32. const S a; // Allocates memory
  33. const S c(a);
  34. cout << c(1) << endl;
  35. S b(a); // Also points to memory allocated for a
  36. b(1) = 3; // Generates an exception
  37. cout << b(1) << endl; // never reached
  38. }
  39. catch (exception &e)
  40. {
  41. cout << "exception: " << e.what() << endl;
  42. }
  43. return 0;
  44. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
42
exception: non-const operation attempted