我習慣於在表達不應該爲null的指針時使用__attribute__((nonnull))
。何時使用「__attribute __((nonnull))」vs「not_null <T*>」?
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);
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的版本,我就應該總是代替__attribute__((nonnull))
現在可以使用not_null<T*>
?
我一直認爲編譯器屬性可能有助於優化,但包裝器版本解析爲未分配的指針。
有一個問題,是'__attribute __ (非空))在主要編譯器之間移植? – WhiZTiM
爲什麼不使用參考或span? – Jarod42