在C代码中使用#Define NullPTR有没有缺点
Is there any downside to having a #define nullptr in C code?
我正在编写一些标题文件,这些文件将由C 代码包含,也包含在C代码中。我希望标题源代码保持一致,并始终使用" nullptr",而不是这些标题中的null(或整数常数0)。
这提出了添加一件代码的可能性,例如:
#ifndef __cplusplus
#define nullptr 0 /* or ((void *)0) */
#endif
或替代:
#include <stdio.h>
#ifndef __cplusplus
#define nullptr NULL
#endif
编辑:或来自Ben Voigt的建议:
#ifndef __cplusplus
static const void *nullptr = 0;
#endif
问题是,这样做的缺点是什么?是否有一些理由将NULLPTR添加到C 而不将其添加到C中?当C 和C必须互操作时,这似乎可以使代码更加一致和可读。
编辑:示例标头
#ifdef __cplusplus
extern "C" {
#endif
extern struct MyStruct *globalMyStruct;
extern int myFunc(struct MyStruct *ptr,int arg);
#ifdef __cplusplus
}
#endif
#define MYMACRO(x) ((globalMyStruct!=nullptr) ? myFunc(globalMyStruct,(x)) : -1)
即使my -struct是C 对象,也可以包含上述标头文件并使用mymacro定义是合法的。我想在C和C 文件中包括上述标头代码。但是,如果我从c文件中包括上述标头,则由于使用nullptr。
对于C代码,将指针包含到C 对象是完全有效的,并且可以将这些指针作为参数传递给函数(也许这些功能是用C 编写的)。这只是C 的一种方式,C可以连接。
我头顶上的两个缺点:
- null/0和nullptr具有不同的行为(如下所述),您不希望nullptr(macro)和nullptr(语言功能)具有不同的行为,即使它们看起来相同,您会吗?
- 应避免宏(无论如何,在C中尽可能多...)
编辑:我在较旧版本的C (但不是C)中做的事情:
#if __cplusplus >= 201103L || (__cplusplus < 200000 && __cplusplus > 199711L)
//use C++ 11 nullptr
#else
struct nullptr_t
{
template <class T>
operator T* (){return (T*)0;}
}nullptr;
#endif
它模仿nullptr的行为而不是宏。
相关文章:
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 在头文件上包含 cpp 文件是否有缺点?
- 使用 nullptr 作为 std::unordered_map 的键有什么后果吗?
- 提供运算符+或运算符到双向迭代器有什么缺点吗?
- std::atomic_flag不提供加载或存储操作有什么缺点吗?(自旋锁定示例)
- 使用std::tie进行类似golang的错误处理,同时返回结果,是否有缺点?(C++11)
- 从不可复制派生 AbstractBaseClasses (ABC) 是否有缺点?
- 守护进程()有什么缺点吗?
- 在循环体内宣布变量有任何缺点
- 不必要的 else 语句:当可以使用 IF 时,使用 ELSE IF 有什么缺点吗?
- 在shared_ptr的自定义删除器中检查 nullptr 是否有意义?
- C++17标准对在nullptr上调用delete有何规定
- 抛出的例外:阅读访问违规.树是nullptr.如果有此例外的处理程序,则可以安全地继续该程序
- 使用使用"extern "C""的 C 库与使用本机C++库有什么缺点?
- 在C代码中使用#Define NullPTR有没有缺点
- pImpl习语-将私有类实现放在cpp中有什么缺点
- 使用 nullptr 有什么优点
- OOP——使用静态方法有缺点吗
- C++ 模板:模板是否内联?性能有缺点吗?
- 删除指针和将其设置为 nullptr 有什么区别?