When do I use "__attribute __ ((nonnull))" vs "not_null <T *>"?
I'm used 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*/} However, with GSL, there is also a shell type not_null<T*> .
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*/} Assuming language tools should support the GSL version, should I always use not_null<T*> instead of __attribute__((nonnull)) now?
I got the impression that the compiler attribute may help in optimization, but the wrapper version is resolved to an unattributed pointer.
"Should I always use not_null instead of the ((nonnull)) attribute now?
not_null seems like a better approach, and here's why:
__attribute__((nonnull)) seems to be gcc specific, so that means that only gcc can use this attribute for optimization, security, security, static code analyzers (etc., as you call it). This makes it not a good choice if you want to use multiple compilers. For example, Microsoft has __assume which can be used to achieve similar results.
gsl::not_null not part of the standard template library, so there is no guarantee that it will work the same on all compilers. You may find that on some compilers this will not do anything special. However, this is the best choice because not_null can wrap all compiler options to achieve the same result (runtime checking can also be added). But judging by the current implementation (see the Link), there is only support for the Microsoft compiler using __assume (could not find implementations for gcc, but if you have such an opportunity, then using it has an advantage)