| 1 |
#include <fstream> |
| 2 |
#include <iostream> |
| 3 |
#include <string> |
| 4 |
using namespace std; |
| 5 |
|
| 6 |
class String |
| 7 |
{ |
| 8 |
union Ptrs |
| 9 |
{ |
| 10 |
void *vp; |
| 11 |
String *sp; |
| 12 |
size_t *np; |
| 13 |
}; |
| 14 |
|
| 15 |
std::string d_str; |
| 16 |
|
| 17 |
public: |
| 18 |
String(std::string const &txt) |
| 19 |
: |
| 20 |
d_str(txt) |
| 21 |
{} |
| 22 |
~String() |
| 23 |
{ |
| 24 |
cout << "destructor: " << d_str << '\n'; |
| 25 |
} |
| 26 |
static String *construct(istream &in, size_t n) |
| 27 |
{ |
| 28 |
Ptrs p = {operator new(n * sizeof(String) + sizeof(size_t))}; |
| 29 |
*p.np++ = n; |
| 30 |
|
| 31 |
string line; |
| 32 |
for (size_t idx = 0; idx != n; ++idx) |
| 33 |
{ |
| 34 |
getline(in, line); |
| 35 |
new(p.sp + idx) String{ line }; |
| 36 |
} |
| 37 |
|
| 38 |
return p.sp; |
| 39 |
} |
| 40 |
static void destroy(String *sp) |
| 41 |
{ |
| 42 |
Ptrs p = {sp}; |
| 43 |
--p.np; |
| 44 |
for (size_t n = *p.np; n--; ) |
| 45 |
sp++->~String(); |
| 46 |
|
| 47 |
operator delete(p.vp); |
| 48 |
} |
| 49 |
}; |
| 50 |
|
| 51 |
int main() |
| 52 |
{ |
| 53 |
String *sp = String::construct(cin, 5); |
| 54 |
|
| 55 |
String::destroy(sp); |
| 56 |
} |
| 57 |
|
| 58 |
/* |
| 59 |
After providing 5 lines containing, respectively |
| 60 |
alpha, bravo, charley, delta, echo |
| 61 |
the program displays: |
| 62 |
destructor: alpha |
| 63 |
destructor: bravo |
| 64 |
destructor: charley |
| 65 |
destructor: delta |
| 66 |
destructor: echo |
| 67 |
*/ |