简体   繁体   中英

What is being declared here?

I came across this strange looking declaration in some code early this morning (before my cup of black coffee had had a chance to "kick in")...

IField const* f(0);

That looks a bit unusual to me. Can anyone explain what the variable f is?

It's a pointer 'f' of type IField const (or const IField) that is initialized to 0. Same as for instance: const IField *f = 0;

Non-const pointer to constant IField object, initialized with NULL value.

It just a normal object declaration.

Read types right to left:
Cost always binds to the left.

IField const*              f(0);
            ^ Pointer to
       ^^^^^  const
^^^^^^        IField.

So the variable 'f' using value-initialization to set its initial value to 0 is a type of 'Pointer to "const IField"'.

It is the equivalent of:

IField const* f   = 0;

or

IField const* f   = NULL;

This basically means 'f' is a pointer. It points at an IField. The object it points at can not be modified via the pointer. But 'f' is not const so we can change the value of 'f' to point at different objects, but initially it is a NULL pointer.

IField const* f(0);

It uses constructor-style initialisation syntax, and is thus equivalent to:

IField const* f = 0;

In that the null pointer literal is involved, this is similar to:

IField const* f = NULL;

Next, consider that const applies left if there's anything there, and right otherwise, so this is the same too:

const IField* f = NULL;

Is this a syntax that you are more used to?

It's the same as const IField *. (If you had the "const" after the asterisk it would be a pointer to a const, rather than a const pointer.)

It is a pointer to const object refereed by IField *. Same as

const IField*  f(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM