假设我有一个函数,它接收指针。
int functionA(int* a, int* b)
{
...
}我可以在functionA中添加空检查。是否有一种方法可以确保在nullptr作为参数传递时编译时发生错误。
发布于 2022-01-23 10:36:17
是一种方法,我可以确保当nullptr作为参数传递时,编译时就会发生错误。
如果您具体指的是nullptr关键字,那么就算是吧。您可以提供在这种情况下将选择的重载,并将其定义为“删除”。这是工作的,只要你没有显式绕过超载,例如,铸造。
int functionA(int*, std::nullptr_t) = delete;
int functionA(std::nullptr_t, int*) = delete;
// ...
functionA(&i, &j) // OK
functionA(nullptr, &i); // error
functionA(&i, nullptr); // error
functionA(nullptr, nullptr); // error或
NULL
除了以前的重载之外,这还需要为整数添加重载:
int functionA(int*, int) = delete;
int functionA(int, int*) = delete;
// ...
functionA(NULL, &i); // error
functionA(&i, NULL); // error
functionA(NULL, NULL); // error如果您指的是任何带空值的指针,那么就不能这样做,因为函数参数的值通常不能在编译时被知道。
如果您的目标是不使用指针作为迭代器,那么将更安全、更方便地传递引用。
https://stackoverflow.com/questions/70820698
复制相似问题