Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <algorithm>
  4. #include <string>
  5. #include <vector>
  6.  
  7. class COWVector {
  8. public:
  9. COWVector() : state_(new State()) {
  10. state_->ref_count_ = 1;
  11. }
  12.  
  13. ~COWVector() {
  14. if (state_->ref_count_ == 1) {
  15. delete state_;
  16. } else {
  17. state_->ref_count_--;
  18. }
  19. }
  20.  
  21. COWVector(const COWVector& other) : state_(other.state_) {
  22. state_->ref_count_++;
  23. }
  24.  
  25. COWVector& operator=(const COWVector& other) {
  26. if (state_->ref_count_ == 1) {
  27. delete state_;
  28. } else {
  29. state_->ref_count_--;
  30. }
  31. state_ = other.state_;
  32. state_->ref_count_++;
  33. return *this;
  34. }
  35.  
  36. size_t Size() const {
  37. return state_->data_.size();
  38. }
  39.  
  40. void Resize(size_t size) {
  41. CheckDeepCopy();
  42. state_->data_.resize(size);
  43. }
  44.  
  45. const std::string& Get(size_t at) {
  46. return state_->data_.at(at);
  47. }
  48.  
  49. const std::string& Back() {
  50. return state_->data_.back();
  51. }
  52.  
  53. void PushBack(const std::string& value) {
  54. CheckDeepCopy();
  55. state_->data_.push_back(value);
  56. }
  57.  
  58. void Set(size_t at, const std::string& value) {
  59. CheckDeepCopy();
  60. state_->data_.at(at) = value;
  61. }
  62.  
  63. struct State {
  64. int ref_count_;
  65. std::vector<std::string> data_;
  66. };
  67.  
  68. private:
  69. void CheckDeepCopy() {
  70. if (state_->ref_count_ != 1) {
  71. state_->ref_count_--;
  72. state_ = new State({1, state_->data_});
  73. }
  74. }
  75.  
  76. State* state_;
  77. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement