Answer the question
In order to leave comments, you need to log in
How to implement copy on write class?
I don’t really understand how to implement copy on write class for the following code
const CowString str1("hello");
CowString str2 = str1;
REQUIRE(str1.GetData() == str2.GetData());
str2[0] = 'h';
REQUIRE(str1.GetData() == str2.GetData());
str2 += " world";
REQUIRE(str1.GetData() != str2.GetData());
for (const auto ch : str1) {
REQUIRE(std::isalpha(ch));
}
const auto* const str2_data = str2.GetData();
str2[5] = '_';
REQUIRE("hello_world" == str2);
REQUIRE(str2 == "hello_world");
REQUIRE(str2_data == str2.GetData());
str2 = str1;
REQUIRE("hello" == str2);
REQUIRE(str1.GetData() == str2.GetData());
const CowString& const_str2 = str2;
REQUIRE('e' == const_str2.At(1));
auto it1 = str1.begin();
auto it2 = str2.begin();
auto const_it2 = const_str2.begin();
*it2 = 'H';
REQUIRE("Hello" == str2);
REQUIRE("Hello" != str1);
REQUIRE('h' == *it1);
REQUIRE('H' == *it2);
REQUIRE('H' == *const_it2);
Answer the question
In order to leave comments, you need to log in
The class itself stores a smart pointer to the data buffer.
You need a buffer reference counter. Before writing, check that the counter is equal to 1. Otherwise, copy the data and replace the pointer with the new buffer in the current object.
The counter must be stored somewhere along with the buffer and is part of the smart pointer.
You can use std::shared_ptr - this counter is already implemented there ( use_count ).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question