File: strings.cc

package info (click to toggle)
c%2B%2B-annotations 10.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 10,536 kB
  • ctags: 3,247
  • sloc: cpp: 19,157; makefile: 1,521; ansic: 165; sh: 128; perl: 90
file content (76 lines) | stat: -rw-r--r-- 1,423 bytes parent folder | download | duplicates (3)
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
#include <string>
#include <iostream>

using namespace std;

class Strings
{
    std::string *d_memory;
    size_t d_size;
    size_t d_capacity;

    public:
        Strings();
        ~Strings();
        void reserve(size_t request);
        void append(std::string const &next);

    private:
        void reserve();
        void destroy();
};

Strings::Strings()
:
    d_memory(static_cast<string *>(operator new(sizeof(string)))),
    d_size(0),
    d_capacity(1)
{}

void Strings::reserve(size_t request)
{
    if (request <= d_capacity)
        return;
    do
        d_capacity <<= 1;
    while (d_capacity < request);
    reserve();
}

//RESERVE
void Strings::reserve()
{
    using std::string;

    string *newMemory = static_cast<string *>(                  // 1
                            operator new(d_capacity * sizeof(string)));
    for (size_t idx = 0; idx != d_size; ++idx)                  // 2
        new (newMemory + idx) string(d_memory[idx]);
    destroy();                                                  // 3
    d_memory = newMemory;
}
//=

//APPEND
void Strings::append(std::string const &next)
{
    reserve(d_size + 1);
    new (d_memory + d_size) std::string(next);
    ++d_size;
}
//=

Strings::~Strings()
{
    destroy();
}

//DESTROY
void Strings::destroy()
{
    for (std::string *sp = d_memory + d_size; sp-- != d_memory; )
        sp->~string();

    operator delete(d_memory);
}
//=