用C默认构造函数 [英] Default constructor in C
问题描述
有没有一种方法有某种默认构造函数(如C ++的)与结构定义的C用户类型?
我已经有一个宏它就像一个快速初始化(如一个 pthread_mutex
),但我想知道,如果你可以通过任何机会,有部分(或全部在填写申报一个结构的)领域。
例如,用 pthread_mutex
的例子,我想
pthread_mutex_t my_mutex;
有尽可能
同样的效果 pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
您可以创建一个指针指向的结构初始化功能。这是常见的做法。
此外,创造一个结构和初始化函数(如工厂) - 所以从来没有一个时间,其中的结构是初始化中的客户code。当然 - 假定人们按照惯例,使用构造/工厂...
可怕的伪code上的malloc或免费的没有错误检查
somestruct * somestruct_factory(/ *每个HAPS一些初始化AGRS?* /)
{
MALLOC一些东西
填写一些东西
返回指针malloced东西
}
无效somestruct_destructor(somestruct *)
{
做清理的东西,也是免费的指针
免费(somestruct);
}
有人可能会一起去,并解释如何一些C ++初preprocessors /编译器的工作做这一切的温度。
Is there a way to have some kind of default constructor (like a C++ one) for C user types defined with a structure?
I already have a macro which works like a fast initializer (like the one for pthread_mutex
) but I wanted to know if you can by any chance have some (or all) fields of a struct filled at declaration.
For instance, with the pthread_mutex
example, I would like
pthread_mutex_t my_mutex;
to have the same effect as
pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER;
You can create initializer functions that take a pointer to a structure. This was common practice.
Also functions that create a struct and initialize it (like a factory) - so there is never a time where the struct is "uninitialized" in the "client" code. Of course - that assumes people follow the convention and use the "constructor"/factory...
horrible pseudo code with NO error checking on malloc or free
somestruct* somestruct_factory(/* per haps some initializer agrs? */)
{
malloc some stuff
fill in some stuff
return pointer to malloced stuff
}
void somestruct_destructor(somestruct*)
{
do cleanup stuff and also free pointer
free(somestruct);
}
Someone will probably come along and explain how some early C++ preprocessors/compilers worked to do this all in C.
这篇关于用C默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!