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

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

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

Author24 — интернет-сервис помощи студентам
Не особо понимаю, как реализовать 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
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
01.06.2019, 17:06
Ответы с готовыми решениями:

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

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

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

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

0
01.06.2019, 17:06
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
01.06.2019, 17:06
Помогаю со студенческими работами здесь

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

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

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

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


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

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru