Clang Attributes是Clang提供的一种注解,开发者用于向编译器表达某种要求。
参数静态检查
void printAge(int age) __attribute__((enable_if(age < 18, "age greater than 18")))
{
cout << age << endl;
}
复制代码
函数重载
#include <stdio.h>
__attribute__((overloadable)) void func(long obj)
{
printf("long %ld\n", obj);
}
__attribute__((overloadable)) void func(int obj)
{
printf("int %d\n", obj);
}
__attribute__((overloadable)) void func(double obj)
{
printf("double %f\n", obj);
}
int main()
{
func(1L);
func(2);
func(1.1);
return 0;
}
复制代码
构造函数和析构函数
#include <iostream>
__attribute__((constructor)) void before()
{
std::cout<<"在main之前调用"<<std::endl;
}
int main(int argc, const char * argv[])
{
std::cout<<"main"<<std::endl;
return 0;
}
__attribute__((destructor)) void after()
{
std::cout<<"在main之后调用"<<std::endl;
}
复制代码
一个不可被继承的类(Final Class)
__attribute__((objc_subclassing_restricted)) @interface FinalClass : NSObject
@end
@interface Subclass : FinalClass
@end
复制代码
子类重写方法时没调用父类的方法在编译时给出警告
@interface Test : NSObject
- (void)someFunc __attribute__((objc_requires_super));
@end
@implementation Test
- (void)someFunc
{
NSLog(@"called on Test");
}
@end
@interface Subclass : Test
@end
@implementation Subclass
- (void)someFunc
{
}
@end
复制代码
GC
#import <Foundation/Foundation.h>
@interface Test : NSObject
@end
@implementation Test
- (void)dealloc
{
NSLog(@"Test's dealloc");
}
@end
void CocoaClassCleanup(__strong NSString **str)
{
NSLog(@"%@",*str);
}
void customedClassCleanup(__strong Test **t)
{
NSLog(@"%@",*t);
}
void primitiveCleanup(int *i)
{
NSLog(@"%d",*i);
}
int main(int argc, const char * argv[])
{
@autoreleasepool
{
NSString *s __attribute__((cleanup(CocoaClassCleanup))) = @"s";
Test *t __attribute__((cleanup(customedClassCleanup))) = [Test new];
int i __attribute__((cleanup(primitiveCleanup))) = 1;
}
return 0;
}
复制代码