Default constructor in C

后端 未结 13 690
孤街浪徒
孤街浪徒 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:44

    Here's a little macro magic around malloc(), memcpy() and C99 compound literals:

    #include 
    #include 
    #include 
    
    #define new(TYPE, ...) memdup(&(TYPE){ __VA_ARGS__ }, sizeof(TYPE))
    
    void * memdup(const void * obj, size_t size)
    {
        void * copy = malloc(size);
        return copy ? memcpy(copy, obj, size) : NULL;
    }
    
    struct point
    {
        int x;
        int y;
    };
    
    int main()
    {
        int * i = new(int, 1);
        struct point * p = new(struct point, 2, 3);
    
        printf("%i %i %i", *i, p->x, p->y);
    
        return 0;
    }
    

提交回复
热议问题