summaryrefslogtreecommitdiff
path: root/tools/bad_thing.h
blob: ee988dcfc1ed23098e2a5ffe81be64d6535d013d (plain)
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
#ifndef BAD_THING_H
#define BAD_THING_H
class payloader{
public:
  int refcount;
  char str[0];
};

class bad_thing: public std::exception{
  payloader* load;
  char* &raw;

public:
  virtual const char* what() const throw() {
    return load->str;
  }
  bad_thing();
// copy constructor.
// It's OK to copy a pointer to the refcount,
// but it would not be OK to copy the refcount!
  bad_thing(const bad_thing &other)
   : load(other.load), raw((char*&) load)
  {
    load->refcount++;
    //xx std::cerr << "Copied! --> " << load->refcount << std::endl;
  }

  bad_thing(const std::string msg)
  : raw((char*&) load)
  {
    size_t len = msg.size();
    raw = new char[1+len + sizeof(payloader)];
    load->refcount = 1;
    for (unsigned int ii = 0; ii < len; ii++){
      load->str[ii] = msg[ii];
    }
    load->str[len] = 0;
  }
  ~bad_thing() throw() {
    if (--load->refcount) return;
    //xx  std::cerr << "delete!" << std::endl;
    delete[] raw;
  }
};
#endif