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
|
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
class String
{
union Ptrs
{
void *vp;
String *sp;
size_t *np;
};
std::string d_str;
public:
String(std::string const &txt)
:
d_str(txt)
{}
~String()
{
cout << "destructor: " << d_str << '\n';
}
static String *construct(istream &in, size_t n)
{
Ptrs p = {operator new(n * sizeof(String) + sizeof(size_t))};
*p.np++ = n;
string line;
for (size_t idx = 0; idx != n; ++idx)
{
getline(in, line);
new(p.sp + idx) String(line);
}
return p.sp;
}
static void destroy(String *sp)
{
Ptrs p = {sp};
--p.np;
for (size_t n = *p.np; n--; )
sp++->~String();
operator delete (p.vp);
}
};
int main()
{
String *sp = String::construct(cin, 5);
String::destroy(sp);
}
/*
After providing 5 lines containing, respectively
alfa, bravo, charlie, delta, echo
the program displays:
destructor: alfa
destructor: bravo
destructor: charlie
destructor: delta
destructor: echo
*/
|