简体   繁体   中英

What's the difference between typedef const struct *CGPath and typedef struct *CGPath?

I've found this in the CGPath.h header file. I'm curious what this const thing does?

typedef struct CGPath *CGMutablePathRef;
typedef const struct CGPath *CGPathRef;

My guess: If I typedef something as const, it's constant so immutable and can't be changed in any way. Does that make sense?

Yes the const means you cannot change the path externally.


For CoreFoundation-based libraries though, the const is more a hack to allow mutable objects to use immutable methods without casting, and not vice-versa. That means

CGMutablePathRef mpath;
...
CGPathContainsPoint(mpath, ...);

compiles fine because a Foo* can be implicitly converted to a const Foo* , but

CGPathRef path;
...
CGPathAddRect(path, ...);

will throw an error because a const Foo* cannot be safely converted to a Foo* .

const T* means that the type is a pointer and that the pointee cannot be changed via that pointer. (That doesn't necessarily mean that the pointee can never change; it might be modified by a different, non- const reference to it, for example.)

"In any way" might be an overstatement, but you're correct. You'll notice that one is called CGPathRef and the other is CG PathRef. PathRef。

const is from standard C. It means that the dereferenced pointer cannot be assigned to. So I cannot do:

GCPathRef p = &my_path;
*p = new_path;  // generates compiler error

But note that p itself can be changed:

p = &another_path; // this is OK.

It is not a hack at all as another poster has suggested. It has been part of C for generations.

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