c - _construct in C,一个在oop项目中使用的宏

标签 c oop constructor macros

最近,我开始使用C来学习面向对象程序设计。 我在网上找到了一些有趣的 Material 。其中之一是 Github 上的 QMonkey/OOC-Design-Pattern 存储库。 https://github.com/QMonkey/OOC-Design-Pattern

这是我的问题:

下面是QMonkey/OOC-Design-Pattern中的base.h。 这是此 OOP C 项目中使用的基本宏。 找了很多关于#、##、offsetof、container_of的解释。 我唯一搞不懂的是_destruct和_construct的用法。我在哪里可以找到他们的解释?

感谢您的帮助。

#ifndef BASE_H
#define BASE_H

#include <stdlib.h>
#include <stddef.h>

// clang-format off
#define container_of(ptr, type, member)                 \
    ({                              \
        const typeof(((type *)0)->member ) *__mptr = (ptr); \
        (type *)((char *)__mptr - offsetof(type,member));   \
    })

#define new(TYPE, args...) TYPE ## _construct(malloc(sizeof(TYPE)), ## args)
#define delete(TYPE, ptr)   do              \
                {               \
                    TYPE ## _destruct(ptr); \
                    free(ptr);      \
                }               \
                while(0)
// clang-format on

#endif

最佳答案

_construct_destruct 只是使用 token pasting operator, ## 附加到类名的后缀.因此,如果 TYPEMyClass,那么将有名为 MyClass_constructMyClass_destruct 的构造函数/析构函数。

关于c - _construct in C,一个在oop项目中使用的宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37541165/

相关文章:

c - c中的匿名流

c - 这种洪水填充算法有什么问题?

actionscript-3 - 如何列出特定包中的(可能大量)类? (AS3)

node.js - nodejs 模块及其导出之间的差异

java - 构造函数未设置数组

c++ - 首先调用哪个构造函数

c - 为什么宏值为0而不是1?

c++ - 在 C/C++ 中启用高对比度模式

php - PHP 中的包?

c++ - 强制派生类使用基类的构造函数