Smart pointers/safe memory management for C?

后端 未结 9 476
闹比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:17

    You can define macros, for example BEGIN and END, to be used in place of braces and trigger automatic destruction of resources that are exiting their scope. This requires that all such resources are pointed to by smart pointers that also contain pointer to the destructor of the object. In my implementation I keep a stack of smart pointers in heap memory, memorize the stack pointer at entry to a scope, and call destructors of all resources above the memorized stack pointer at scope exit (END or macro replacement for return). This works nicely even if setjmp/longjmp exception mechanism is used, and cleans up all the intermediate scopes between the catch-block and the scope where the exception was thrown, too. See https://github.com/psevon/exceptions-and-raii-in-c.git for the implementation.

    0 讨论(0)
  • 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 !
    */
    
    0 讨论(0)
  • 2020-12-07 18:26

    It's difficult to handle smart pointers in raw C, since you don't have the language syntax to back up the usage. Most of the attempts I've seen don't really work, since you don't have the advantages of destructors running when objects leave scope, which is really what makes smart pointers work.

    If you're really worried about this, you might want to consider just directly using a garbage collector, and bypassing the smart pointer requirement altogether.

    0 讨论(0)
提交回复
热议问题