Memory Usage of an Empty Type Object

Since sizeof

there is 1 byte of empty class in C ++ , does the following code have:

class A
{
};

int main()
{
    A a;
    char* p = reinterpret_cast<char*>(&a);
    *p = 'a';
}

      

I know it is nearly useless, but just wanted to see if I could do it. It compiles and works fine on MSVC2010.

+3


source to share


1 answer


C ++ 03 Standard 1.8 C ++ Object Model:

Relevant parts are Β§1 : an object is a storage area ... Some objects are polymorphic ... For other objects, the interpretation of the values ​​found in it is determined by the type of expressions used to access them. "

In your example a

, it is an auto-retention object that is freed when execution goes out of scope. Basically, the memory it resides in is available to you and you can store wherever you want:

int i;
char* myStr = reinterpret_cast<char*>(&i);
myStr[0] = 'H';
myStr[1] = 'i';
myStr[2] = '!';
myStr[3] = '\0';
std::cout << myStr;

      

(Full example here )

What you should consider here is the lifetime of the object you are "abusing" in this way, ie. if you still retain a pointer to that memory even after the object has been freed, accessing that memory will result in w90> behavior .



Just remember that just because language allows you to do something, it doesn't mean that you should. Use the features of this language the way they were meant to be used. After all, you don't write codes just to "make it work".


And to your question about the size of an empty class, the same part of the standard also says:

Β§4 . If a complete object, data item (9.2), or array element has a class type, its type is considered the most derived class , distinguish it from the class type of any base class subobject; the object of the most derived class is called the most derived object .

Β§5 . If it is not a bit-field (9.6), the most derived object must be of nonzero size and must occupy one or more storage bytes >. Base class subjects can be of size zero. Object of type POD (3.9) must occupy contiguous storage bytes.

So the standard is guaranteed that objects of an empty class like yours will be at least 1 byte in size .

+1


source







All Articles