Smart pointers/safe memory management for C?

后端 未结 9 595
闹比i
闹比i 2020-12-07 17:31

I, and I think many others, have had great success using smart pointers to wrap up unsafe memory operations in C++, using things like RAII, et cetera. However, wrapping memo

9条回答
  •  被撕碎了的回忆
    2020-12-07 18:18

    Sometimes i use this approach and it seems good :)
    
    Object *construct(type arg, ...){
    
        Object *__local = malloc(sizeof(Object));
        if(!__local)
            return NULL;
        __local->prop_a = arg;
        /* blah blah */
    
    
    } // constructor
    
    void destruct(Object *__this){
    
       if(__this->prop_a)free(this->prop_a);
       if(__this->prop_b)free(this->prop_b);
    
    } // destructor
    
    Object *o = __construct(200);
    if(o != NULL)
       ;;
    
    // use
    
    destruct(o);
    
    /*
      done !
    */
    

提交回复
热议问题