Default constructor in C

后端 未结 13 653
孤街浪徒
孤街浪徒 2020-12-07 21:02

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 in

13条回答
  •  太阳男子
    2020-12-07 21:42

    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.

提交回复
热议问题