clang attribute

丟的錢找到了發表於2018-03-28

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;
}
複製程式碼

相關文章