LoginSignup
2
2

More than 5 years have passed since last update.

[C++11] sizeof

Last updated at Posted at 2016-03-09

We usually use the sizeof to evaluate the size of a instance (class or struct) or variable. Such as:

class Car {
public:
    int id;
    string name;
    static int count;
};

int main() {
    Car p;
    cout << sizeof(p) << endl;           // 4
    cout << sizeof(Car::count) << endl;  // 4
    return 0;
}

In C++98, we can not evaluate the size of id without creating a instance with sizeof, but we can do it with C++11.

//C++98: error: invalid use of non-static data member 'id'
//C++11: 4
cout << sizeof(Car::id) << endl;

In C++98, if we do the same thing, we maybe do something like this:

cout << sizeof(((Car*)0)->id) << endl; // 4

It's very clear to see that the way of C++11 is easier to read.

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2