Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
0 / 0 / 0
Регистрация: 30.05.2019
Сообщений: 7

Реализовать Copy on Write COW

01.06.2019, 17:06. Показов 2395. Ответов 0
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Не особо понимаю, как реализовать COW для вот этого кода

Main.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include "mystring.h"
using std::cin;
using std::cout;
using my_namespace::MyString;
int main()
{
    MyString a("lama ");
    const MyString b("star ");
    MyString c;
    c = a + b;
    a += b;
    std::cout << a<<std::endl;
    std::cout << c<<std::endl;
    std::cout << b<<std::endl;
 
    if(a == b)
        std::cout << "yep"<<std::endl;
    else
        std::cout << "ops"<<std::endl;
 
    if(!a.isEmpty())
        std::cout << "(a)string is not empty"<<std::endl;
 
    std::cout << a.reverse()<<std::endl;
 
    if (a >= b)
        std::cout << "good"<<std::endl;
    else
        std::cout << "not good"<<std::endl;
 
    std::cout <<  c.size() <<std::endl;
    try
    {
        std::cout << c[11];
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
    }
 
    MyString k;
    k = -2;
    std::cout << std::endl << "the string by numb is: " << k << std::endl;
    return 0;
}

Mystring.cpp

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#include "mystring.h"
#include <exception>
#include <cmath>
#include <sstream>
#include <utility>
#include <algorithm>
using std::runtime_error;
using my_namespace::MyString;
 
MyString::MyString()
{
    this->_size=0;
    std::cout<<"&&&&&simple constructor&&&&&"<<std::endl;
    this->_data = new char[1];
    this->_data[0] ='\0';
    this->_hash = 0;
    this ->_changed = true;
}
 
MyString::~MyString()
{
    delete[] this->_data;
    this-> _size = 0;
}
 
MyString::MyString(const MyString &string)
    : _data(new char[string._size + 1])
    , _size(string._size)
{
    std::cout<<"cp";
    strcpy(this->_data, string._data);
}
 
MyString::MyString(const char* string)
    : _data(new char[strlen(string) + 1])
    , _size(strlen(string))
{
    std::cout<<"S";
    strcpy(this->_data, string);
}
 
//MyString::MyString(my_namespace::MyString &&other)
//{
//    _data = other._data;
//    other._data = nullptr;
//}
 
//my_namespace::MyString &MyString::operator=(my_namespace::MyString &&other)
//{
//    swap (*this, other);
//    return *this;
//}
 
MyString& MyString::operator= (const MyString &other)
{
    std::cout<<"=";
    MyString tmp(other._data);
    swap(*this, tmp);
    return *this;
}
 
MyString& MyString::operator= (const char* chars)
{
    std::cout<<"&&&&copy = oper for string&&&&"<<std::endl;
    MyString tmp(chars);
    swap(*this, tmp);
    return *this;
}
 
MyString& MyString::operator=(int num) {
    std::cerr << "N";
    std::stringstream ss;
    ss << num;
    MyString res(ss.str().c_str());
    std::cerr << "N";
    swap(*this, res);
    std::cerr << "N";
 
    return *this;
}
 
unsigned int MyString::size()
{
     return this->_size;
}
 
bool MyString::isEmpty()
{
    std::cout<<"&&&&isempty check&&&&"<<std::endl;
    return !this->_size;
}
 
MyString MyString::reverse()
{
    std::cout<<"&&& reverse: ";
    char* new_data = new char[_size + 1];
    new_data[_size] = '\0';
    for (int i = 0; i < _size; ++i)
        new_data[i] = _data[_size - 1 - i];
    delete[] _data;
    _data = new_data;
 
    this->_changed=true;
    this->set_hash();
    return *this;
}
 
MyString MyString::operator+ (const MyString &other)
{
    std::cout <<"&&&&simple operator +&&&&"<<std::endl;
 
    MyString sum ;
    sum._size = this->_size+other._size;
    sum._data = new char[sum._size];
    strcpy(&sum._data[0], &this->_data[0]);
    strcpy(&sum._data[this->size()], &other._data[0]);
    sum._data[sum._size] = '\0';
 
    sum._changed=true;
    sum.set_hash();
    return sum;
}
 
MyString MyString::operator+(const char * other_chars)
{
    std::cout<<"&&&&string operator +&&&&"<<std::endl;
    MyString sum ;
    sum._size = this->_size+strlen(other_chars);
    sum._data = new char[sum._size + 1];
    strcpy(&sum._data[0], &this->_data[0]);
    strcpy(&sum._data[this->size()], &other_chars[0]);
    sum._data[sum._size] = '\0';
 
    sum._changed=true;
    sum.set_hash();
    return sum;
}
 
MyString& MyString::operator+=(const MyString& other)
{
    std::cout <<"&&&&simple operator +&&&&"<<std::endl;
    *this = *this + other ;
    this->_changed = true;
    this->set_hash();
    return *this;
}
 
MyString& MyString::operator+=(const char *other)
{
    std::cout <<"&&&&&string operator +=&&&&&"<<std::endl;
    MyString str(other);
    *this = *this + str;
    this->_changed = true;
    this->set_hash();
    return *this;
}
 
bool MyString::operator== (const MyString& string)
{
    std::cout <<"&&&&simple operator ==&&&&"<<std::endl;
    return !strcmp(this->_data, string._data);
}
 
bool MyString::operator== (const char* other_chars)
{
    std::cout <<"&&&&string operator ==&&&&"<<std::endl;
    return !strcmp(this->_data, other_chars);
}
 
char& MyString::operator[](int indx)
{
    if(indx < 0 || indx >= this->_size) {
        throw runtime_error("there is no spot in string with this index \n");
    }
    return this->_data[indx];
}
 
char MyString::operator[](int indx)const
{
    if(indx < 0 || indx >= this->_size) {
        throw runtime_error("there is no spot in string with this index \n");
    }
    return this->_data[indx];
}
 
MyString::operator const char*() const {
    return this->_data;
}
 
const long MyString::set_hash() const
{
    if(!this->_changed)
        return this->_hash;
 
    this->_hash = 0;
    for(int i = 0; i < this->_size; ++i) {
        this->_hash += this->_data[i];
    }
 
    this->_changed = false;
    std::cout<<"&&&&&hash: ";
    return this->_hash;
}
 
bool MyString :: operator<=(const MyString& string)
{
    return strlen(this->_data) <= strlen(string._data);
}
 
bool MyString:: operator<= (const char* string)
{
    return strlen(this->_data) <= strlen(string);
 
}
 
bool MyString:: operator>=(const MyString& string)
{
    return strlen (this->_data) >= strlen(string._data);
}
 
bool MyString :: operator>=(const char *string )
{
    return strlen (this->_data) >= strlen(string);
}
 
int MyString::get_number() {
//    int result = 0;
//    bool positive = true;
//    int start_pos = 0;
//    if(this->_data[0]=='-') {
//           positive =false;
//           start_pos++;
//    }
 
//    for(int i = start_pos; i < this->_size; ++i)
//    {
//        char digit = this->_data[i];
//        if (digit >= '0' && digit <= '9') {
//            result = result * 10 + (digit - '0');
//        } else {
//            throw std::logic_error("cannot convert that string to number");
//        }
//    }
 
//    if (!positive)
//        result *= -1;
 
//    return result;
    return atoi(_data);
}
 
MyString MyString::number(int num)
{
    std::stringstream ss;
    ss << num;
    MyString res(ss.str().c_str());
    return res;
}
 
std::ostream& my_namespace::operator<<(std::ostream &stream, const MyString &string)
{
    stream << string._data;
    return stream;
}
 
std::istream& my_namespace::operator>>(std::istream &stream, const MyString &string)
{
    stream >> string._data;
    return stream;
}
 
void my_namespace::swap(my_namespace::MyString &l, my_namespace::MyString &r)
{
    using std::swap;
    swap (l._data , r._data);
    swap (l._size, r._size);
}

mystring.h

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#pragma once
#include <iostream>
#include <cstring>
#include <cstdlib>
 
namespace my_namespace
{
    class MyString
    {
    public:
        MyString();
        MyString(const MyString& string);
        MyString(const char* string);
//        MyString(MyString&& other) noexcept;
 
 
        MyString& operator= (const MyString &other);
        MyString& operator= (const char * string);
//        MyString& operator=(MyString&& other);
 
        friend void swap (MyString& l, MyString& r);
 
        MyString operator+ (const MyString &string);
        MyString operator+ (const char * string);
 
        MyString& operator+= (const MyString& string);
        MyString& operator+=(const char *sring);
 
        char& operator[](int indx);
        char  operator[](int indx) const;
 
        operator const char*() const;
 
        bool operator== (const MyString& string);
        bool operator== (const char* string);
 
        bool operator<=(const MyString& string);
        bool operator<= (const char* string);
 
        bool operator>=(const MyString& string);
        bool operator>=(const char *string );
 
        MyString& operator=(int number);
        int get_number();
        static MyString number(int num);
 
        MyString reverse();
        bool isEmpty();
        unsigned int size();
        const long set_hash() const;
 
        friend std::ostream& operator<<(std::ostream& stream , const MyString &string);
        friend std::istream& operator>> (std::istream& stream, const MyString &string);
 
        ~MyString();
    private:
        char* _data;
        mutable unsigned int _size;
        mutable long _hash;
        mutable bool _changed;
    };
 
    void swap(MyString &l, MyString &r);
 
    std::ostream &operator<<(std::ostream &stream, const MyString &string);
    std::istream &operator>>(std::istream &stream, const MyString &string);
 
} // of namespace my_namespace
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
01.06.2019, 17:06
Ответы с готовыми решениями:

COW copy on write, класс MyString
Нужно реализовать COW, но никак все не получается main.cpp #include &lt;iostream&gt; #include &quot;mystring.h&quot; using...

copy on write оптимизация
Требуется сделать copy on write оптимизацию, но я не знаю как мне верно перенаправлять указатели / ссылки :( Оптимизация состоит в том,...

Пример функции для изменения региона защиты памяти процесса с Read Only на Write Copy
будьте добры привести пример функции для изменения региона защиты памяти процесса с Read Only на Write Copy VirtualAlloc - не подходит

0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
01.06.2019, 17:06
Помогаю со студенческими работами здесь

Fork и copy-on-write
Здравствуйте. Подскажите, пожалуйста: я написал простую программу, использующую системный вызов fork(). Насколько я понимаю,что при fork'e...

Copy-on-write при создании классов
Добрый день. Читая посты Работа с памятью (и всё же она есть) и Изучаем PHP изнутри. Zval возник такой вопрос: Пример: есть...

Реализовать функции Copy и Pos
А) Выделения подстроки и заданной строки(copy) b) определения, выходит ли указанная подстрока в заданную строку (pos) В основной...

Реализовать функции Copy и Revert
1) Реализовать функцию Copy(s, i1, i2), возвращающую строку, полученную копированием из строки s символов, начиная с i1-го и заканчивая...

Message "Write conflict" with "Save record", "Copy to clipboard", "Drop changes" buttons
Здравствуйте. Получив это сообщение нажимаю на &quot;Save record&quot; и продолжаю работать. Скажите, возможно ли это сообщение не получать, а...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11680&amp;d=1772460536 Одним из. . .
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка библиотек: SDL3, Box2D, FreeType, SDL3_ttf, SDL3_mixer и SDL3_image из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru