什么时候使用"__attribute __((nonnull))"与"not_null< T *>"相比? [英] When do I use "__attribute__((nonnull))" vs "not_null<T*>"?

查看:165
本文介绍了什么时候使用"__attribute __((nonnull))"与"not_null< T *>"相比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于在表示不应为null的指针时使用__attribute__((nonnull)).

I'm accustomed to using __attribute__((nonnull)) when expressing pointers that should not be null.

void f(int* ptr __attribute__((nonnull)));

int main(){
    int* ptr = new int(1);
    f(ptr);
}
void f(int* ptr){/*impl*/}

但是,对于GSL,还有not_null<T*>包装器类型.
void function1(gsl :: not_null n);

However, with the GSL, there is also the not_null<T*> wrapper type.
void function1(gsl::not_null n);

void f(gsl::not_null<int*> n);

int main(){
    int* ptr = new int(1);
    f(ptr);
}
void f(gsl::not_null<int*> n){/*impl*/}

假设那里有支持GSL版本的语言工具,我现在应该一直使用not_null<T*>代替__attribute__((nonnull))吗?

Assuming the language facilities are there to support the GSL version, should I always be using not_null<T*> in place of __attribute__((nonnull)) now?

我一直认为,编译器属性可能有助于优化,但是包装器版本解析为一个未归因的指针.

I've been under the impression that the compiler attribute may aid in optimizations, but the wrapper version resolves down to an unattributed pointer.

推荐答案

"我现在应该一直使用not_null代替属性(((nonnull)))吗?

"should I always be using not_null in place of attribute((nonnull)) now?

not_null似乎是更好的方法,这就是原因:

not_null seems the better approach and here is why:

__attribute__((nonnull)) 似乎是特定于gcc的,因此这意味着只有gcc可以将此属性用于优化,安全性,安全性,静态代码分析器(等,您命名).如果要使用多个编译器,这将不是一个很好的选择. Microsoft例如有 __assume 可用于实现类似的结果.

__attribute__((nonnull)) seems to be gcc specific so this means that only gcc could use this attribute for optimizations, safety, security, static code analyzers (etc, you name it). This makes it not a very good choice if you want to use multiple compilers. Microsoft has for example __assume which can be used to achieve a similar results.

gsl::not_null 不属于标准模板库,因此不能保证它会以相同的方式在所有编译器上运行.您可能会发现,在某些编译器上,它绝对没有什么特别的.但是,这是一个更好的选择,因为not_null可以包装所有编译器变体以获得相同的结果(也可以添加运行时检查).但是从当前的实现(请参阅链接)来看,仅支持使用__assume的Microsoft编译器(找不到gcc的实现,但是如果您有gcc的实现,那么使用它是一个优势)

gsl::not_null is not part of the Standard Template Library so there is no guarantee that it will work on all compilers the same way. You might find that on some compilers it will do absolutely nothing special. However this is a better choice because not_null could wrap all compiler variations to achieve the same result (also runtime checking can be added). But judging from the current implementation (see link) there is only support for Microsoft compiler using __assume (could not find implementations for gcc, but if you have one then it's an advantage to use it)

这篇关于什么时候使用"__attribute __((nonnull))"与"not_null&lt; T *&gt;"相比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆