The analysis and function of empty array, empty class and Class hollow array in C + +

Source: Internet
Author: User

Transferred from: http://blog.sina.com.cn/s/blog_93b45b0f01015s95.html

We often encounter these problems:

(1) C + + defines an empty class, what is its size (sizeof)?

(2) The size of a class that has only one char data member?

(3) Can I define an empty array?

(4) Where does the pointer pointing to an empty array name point to?

(5) What is the use of empty classes?

(6) What is the use of an empty array?

Wait a minute......

These questions, the author in this article all do a more detailed analysis and understanding.

1. What is sizeof?

First, we need to understand what sizeof is.

To be exact, for a strongly typed language like C + +, at some point the size of the object's type is deterministic, and this information can be determined directly at compile time, so we have to understand that sizeof is not a function, but a macro that returns the size of the object, which can be either an object or a type.

What we need to understand is that at the end of the compilation, the location of sizeof is directly replaced with a constant, and we use a simple and intuitive experiment to confirm that:

int main () {

int a=2;

int b[sizeof (a)];

Cout<<sizeof (b)/sizeof (int) <<endl;

}

If sizeof is acting as a function, then this is not possible to compile successfully, because it is necessary to define the array on the stack (or constant expression).

So that we can know:

sizeof (i++);

In this sentence, I is not possible to add 1, because this sentence at compile time has been converted to the corresponding constant, and compile time is not run, which is often one of the pitfalls.

2. Size of the empty class

Many people know that an empty class (the latter being an empty class object) uses sizeof when the result is 1. I believe everyone knows, think about it, if it's really empty class. Then for the same empty class of objects will not occupy space, does not occupy space means that can not be distinguished.

(one might say that we only assign object names and do not allocate space, so you will make the whole C + + language An empty class, and the associated empty class object design a special set of rules that the language becomes very unreasonable).

So, the choice of C + + is to automatically insert a char type into an empty class (only a special treat), so long as the class object will occupy space in the future, it can be distinguished by the address.

3. The role of empty classes

Another question about empty classes is, is it necessary for the C + + language to preserve empty classes? What is the use of an empty class to implement an empty object?

Useful, especially in "generic programming", where empty classes (structs) are very useful:

As mentioned in other articles, we use types (usually empty classes) to differentiate between properties of different classes of objects. (We can actually distinguish it by using constants, but it's easy to tell the difference.)

Using constants to distinguish between methods that need to use if else's run-time to determine which line to execute, and using the method of function overloading, adding an empty class field to the parameter as a method of distinguishing between different functions, when compiling a direct selection, rather than at run time, this is very efficient.

You know, different empty classes are different. They represent different types (although they have the same structure). In STL, it is very common to use empty classes to differentiate between different types of flags, so that targeted optimizations of different classes are made at compile time.

Template <typename a>

void Fun (A a)

{

typedef typename TRAIT<A>::TYPE T;

_fun (A A, * (New T ()));

}

Template <typename a>

void _fun (a A, int)

{

......

}

Template <typename a>

void _fun (A B, float)

{

......

}

Of course, there should be other uses for empty classes. All we know and understand is that empty classes are a useful mechanism in C + +, and empty classes of different names represent different types.

The empty class will be compiled automatically by the compiler to join a char member, not for another, just so that it is the object after the instance occupies space, thus can be distinguished.

4. Empty array

We can define an empty array in C:

int a[0];

When using sizeof, you c guess how much:

0

Well, here's 0, we can understand.

But here's the problem:

Since the previous case for empty classes, because you need to make the object unique positioning, so insert char, then empty array since the size of sizeof is 0, that should be the space, then how to distinguish.

In fact, for an empty array, there is a special explanation in C + + (perhaps the specific implementation is different, here just using gcc,g++).

An empty array name is a pointer (but does not occupy space) to a location:

For structs, an empty array name this pointer points to the first space at the end of the previous member.

For a non-structural problem, an empty array name this pointer points to the same content as the pointer to the previous object (although it is possible that their type is different).

Although, we do not know what the two arrangements have any mystery, or benefits, but it does not matter (the next section will describe the role of empty arrays), but for the empty array of sizeof why can be 0, we have an explanation.

Unlike an empty class, an empty array is an object, not a class. Now that we have this object defined, and it points to a space (although this space may overlap with other places), we can finally divide the different empty arrays.

5. Function of an empty array

In fact, in C, the use of empty arrays is very much.

Problem:

If you want to add a buffer to a struct (representing a function). What would you do?

1) define a fixed-length buffer array member, so the downside is that buffer will be dead.

2) Define a buffer pointer in the constructor (although C is not, but you can use the Initialize function instead) to dynamically create a buffer of a size that needs to be used for this struct.

But that would require us to manage this space in particular (using destructors), or it would be very easy to have a memory leak. Also, a buffer pointer occupies a space.

So in C, there is a clever way to use an empty array to achieve this problem.

Sttuct T

{

int A;

int b;

......

Char buffer[];

};

We know that because buffer does not occupy space, the total size of the T object does not count to buffer.

struct T * p= (t*) malloc (sizeof (T) +buffer_len);

See no, in the claim space, plus buffer_len (the required buffer length), so that the structure and buffer are applied together, (at the end, you can also directly use free to release, you can avoid the independent management structure and buffer).

And we know that the "pointer" to buffer is the Buffer_len space behind the struct.

There is also a benefit if we manage the structure and buffers separately (usually this time the struct is a small fragment). In the application and release of the time, it is easy to create fragments in memory.

And if the above management, the structure, the attachment of this buffer (chunks) together is managed. That would be a wonderful thing. This is the usefulness of an empty array.

6. Class Hollow Array

Class T

{

int a[0];

};

What do you think of the sizeof for this class:

0

You'll think it's a joke, but in fact, it can be done with a careful analysis.

I said earlier. Inserting a char member into an empty class is because you want the program to be able to distinguish between different objects of that class.

And here, we know that because an empty array is not a memory, it is like a pointer to a place, but does not account for memory. But it is true that our class objects can be distinguished by the use of an empty array.

So if the purpose is achieved, then why do you want to add what information?

The analysis and function of empty array, empty class and Class hollow array in C + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.