简体   繁体   English

typedef const struct * CGPath和typedef struct * CGPath有什么区别?

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

I've found this in the CGPath.h header file. 我已经在CGPath.h头文件中找到了它。 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. 我的猜测:如果我将def定义为const,它是常量,因此是不变的,不能以任何方式更改。 Does that make sense? 那有意义吗?

Yes the const means you cannot change the path externally. 是的const表示您不能从外部更改路径。


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. 对于基于的CoreFoundation库虽然, const更是一个黑客,使可变对象使用一成不变的方法,而铸造的,而不是相反。 That means 那意味着

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

compiles fine because a Foo* can be implicitly converted to a const Foo* , but 可以正常编译,因为Foo*可以隐式转换为const Foo* ,但是

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

will throw an error because a const Foo* cannot be safely converted to a Foo* . 因为无法将const Foo*安全地转换为Foo*将引发错误。

const T* means that the type is a pointer and that the pointee cannot be changed via that pointer. const T*表示类型是指针,并且不能通过该指针更改指针。 (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.) (这并不一定意味着该指针对象永远不会改变,它可能由一个不同的,非被修改const参照它,例如)。

"In any way" might be an overstatement, but you're correct. “以任何方式”可能都是夸大其词,但您是对的。 You'll notice that one is called CGPathRef and the other is CG Mutable PathRef. 您会注意到一个称为CGPathRef,另一个称为CG Mutable PathRef。

const is from standard C. It means that the dereferenced pointer cannot be assigned to. const来自标准C。这意味着不能将取消引用的指针分配给它。 So I cannot do: 所以我不能做:

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

But note that p itself can be changed: 但是请注意,p本身可以更改:

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. 它已经成为C语言的一部分了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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