Why use functions like CGRectMake?

我的未来我决定 提交于 2019-12-04 15:56:37

问题


I'm curious why functions like CGRectMake and CGPointMake exist and are widely used. when, instead, you can do:

(CGRect){{x, y}, {width, height}}

surely this is more efficient (though I'm guessing not by much) as there is no function call?

Also you can set the origin and size like:

 (CGRect){origin, size}

and as a mixture:

 (CGRect){origin, {width, height}}

What is the reason for not using this, and preferring the Make functions?


回答1:


It isn't more efficient, actually. The CGRectMake function (and others) are declared as static inline, which means the compiler copy pastes the function code straight into every place it's used:

CG_INLINE CGRect
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)

where

#  define CG_INLINE static inline

You go from

// code
CGRect myRect = CGRectMake(1,2,3,4);
// code

to

// code
CGRect myRect;
myRect.origin.x = 1; myRect.origin.y = 2;
myRect.size.width = 3; myRect.size.height = 4;

which in principle is no different from

CGRect myRect = (CGRect){1,2,3,4};

after compiler optimizations and such.

As said above you add a dependency on CGRect being a struct of 4 numbers aligned a certain way as opposed to using a function that has more guarantee to it.




回答2:


I suppose it is the same old difference between:

  1. adding a dependency in you code from the internal definition of a data structure;

  2. using a function that encapsulates that knowledge and that could "mask" any changes in the underlying data structure.

In principle, CGRect might evolve into a full-blown class with its origin, size, etc, accessors, etc... I am not saying this would be sensible or that it is likely, only that the reason why you use a function to create instances of a data structure has to do with resilience of your code to changes.




回答3:


C99's Compound literal syntax is a somewhat obscure feature. Some people find the Make functions clearer to read, or they find it more familiar. At this stage in toolchain support, it's merely preference.

I'm curious why functions like CGRectMake and CGPointMake exist…

CGRectMake (available since 10.0) preceded OS X's compiler's support of compound literals. Compound literals were officially completed in GCC 3.1 (May 2002).



来源:https://stackoverflow.com/questions/11700535/why-use-functions-like-cgrectmake

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!