c++ - 在 C 代码中使用 #define nullptr 有什么缺点吗?

标签 c++ c

我正在编写一些头文件,这些头文件将包含在 C++ 代码中,也将包含在 C 代码中。我希望 header 源代码保持一致,并且在这些 header 中始终使用“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)

即使MyStruct是一个C++对象,那么C代码包含上述头文件并使用MYMACRO定义也是合法的。我想在 C 和 C++ 文件中包含上面的头代码。但是,如果我从 C 文件中包含上述 header ,那么由于使用了 nullptr,它不会编译。

C 代码包含指向 C++ 对象的指针是完全有效的,并且这些指针可以作为参数传递给函数(也许这些函数是用 C++ 编写的)。这只是 C++ 和 C 可以互操作的一种方式。

最佳答案

我想到了两个缺点:

  • NULL/0 和 nullptr 具有不同的行为 (as explained here) 您不希望 nullptr(宏)和 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 的行为而不是一个宏。

关于c++ - 在 C 代码中使用 #define nullptr 有什么缺点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46160249/

相关文章:

c++ - 创建一个程序来输出 4 个三角平方数

c - 如何在 RDLC 报告中使用动态 Select (sp_executesql) 捕获存储过程的结果集

c - 如何在 C 中保留函数指针?

C++ 编程工具

c++ - 如何在文本模式下安全地混合 std::ifstream 的 tellg、seekg 和 read(*,n) 方法

c++ - 在 Release模式下编译时,大量嵌套循环会导致链接器无休止地运行吗?

c++ - 使聚光灯静止

从 main() 调用函数

c - 为什么 Ken Thompson 在 "Reflections on Trusting Trust"中提到的 C quine 不起作用?

c - Unix 系统调用按升序然后降序打印数字