Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sizeof(this - id) returns 8?

Tags:

c++

I had a very stupid typo in my code...

is.read((char*)&this->id, sizeof(this-id));

missing > character after this-

Interestingly sizeof(this - id) returned 8!

What I think is... since this is a pointer, doing subtraction on this will result in another pointer that is off by value of id which can be anything depending on the value of id.

And... on 64 bit system, pointer is usually 8 bytes!

Am I correct? or missing something?

Below is the class I have.

class IndexItem : public Serializable {
public:
  IndexItem(uint32_t id, std::streampos pos) :
    id(id),
    pos(pos)
  { }
  uint32_t id;
  std::streampos pos;
protected:
  std::ostream& Serialize(std::ostream& os) const override {
    os.write((char*)&this->id, sizeof(this->id));
    os.write((char*)&this->pos, sizeof(this->pos));
    return os;
  }

  std::istream& Deserialize(std::istream& is) override {
    is.read((char*)&this->id, sizeof(this->id));
    is.read((char*)&this->pos, sizeof(this->pos));
    return is;
  }
};
like image 566
Eddie Avatar asked Feb 10 '23 12:02

Eddie


1 Answers

You are correct. You can add or subtract integral types to any pointer, resulting in another pointer and sizeof(this-id)=sizeof(this) which happens to be 8 in your system.

like image 51
toth Avatar answered Feb 13 '23 02:02

toth