tags:

views:

65

answers:

4

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?

+1  A: 

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

Rob Napier
+2  A: 

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*.

KennyTM
+2  A: 

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.)

jamesdlin
+1  A: 

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.

Emil