clang attribute

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;
}
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值