Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <algorithm>
- #include <string>
- #include <vector>
- class COWVector {
- public:
- COWVector() : state_(new State()) {
- state_->ref_count_ = 1;
- }
- ~COWVector() {
- if (state_->ref_count_ == 1) {
- delete state_;
- } else {
- state_->ref_count_--;
- }
- }
- COWVector(const COWVector& other) : state_(other.state_) {
- state_->ref_count_++;
- }
- COWVector& operator=(const COWVector& other) {
- if (state_->ref_count_ == 1) {
- delete state_;
- } else {
- state_->ref_count_--;
- }
- state_ = other.state_;
- state_->ref_count_++;
- return *this;
- }
- size_t Size() const {
- return state_->data_.size();
- }
- void Resize(size_t size) {
- CheckDeepCopy();
- state_->data_.resize(size);
- }
- const std::string& Get(size_t at) {
- return state_->data_.at(at);
- }
- const std::string& Back() {
- return state_->data_.back();
- }
- void PushBack(const std::string& value) {
- CheckDeepCopy();
- state_->data_.push_back(value);
- }
- void Set(size_t at, const std::string& value) {
- CheckDeepCopy();
- state_->data_.at(at) = value;
- }
- struct State {
- int ref_count_;
- std::vector<std::string> data_;
- };
- private:
- void CheckDeepCopy() {
- if (state_->ref_count_ != 1) {
- state_->ref_count_--;
- state_ = new State({1, state_->data_});
- }
- }
- State* state_;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement