vendredi 24 avril 2015

Is this union compatible with strict-alising rules?

Is it OK to use both parts of a union if you know the parts don't overlap? Like in this example, is it OK to use both buf[31] as well as ps?

struct PtrSize {
  const char *data;
  size_t size;
};

class SmallStringOrNot {
  union {
    PtrSize  ps;
    char     buf[32];
  } pb;

public:
  bool IsSmallString() const {
    return pb.buf[31] != 0;
  }
  SmallStringOrNot(const char *str) {
    size_t len = strlen(str);
    if (len && len < 31) {
      memcpy(pb.buf, str, len);
      pb.buf[31] = len;
    } else {
      pb.ps.data = str;
      pb.ps.size = len;
      pb.buf[31] = 0;
    }
  }
  PtrSize AsPtrSize() const {
    if (IsSmallString()) {
      return PtrSize{pb.buf, pb.buf[31]};
    } else {
      return pb.ps;
    }
  }
};

Aucun commentaire:

Enregistrer un commentaire