Will the below code cause memory leak in c++

前端 未结 7 1915
醉话见心
醉话见心 2020-12-05 08:13
class someclass {};

class base
{
    int a;
    int *pint;
    someclass objsomeclass;
    someclass* psomeclass;
public:
    base()
    {
        objsomeclass = so         


        
7条回答
  •  误落风尘
    2020-12-05 08:40

    Both new's will be leaked.

    Assign the address of the heap created objects to named smart pointers so that it will be deleted inside the smart pointers destructor that get call when the exception is thrown - (RAII).

    class base {
        int a;
        boost::shared_ptr pint;
        someclass objsomeclass;
        boost::shared_ptr psomeclass;
    
        base() :
            objsomeclass( someclass() ),
            boost::shared_ptr psomeclass( new someclass() ),
            boost::shared_ptr pint( new int() )
        {
            throw "constructor failed";
            a = 43;
        }
    };
    

    Now psomeclass & pint destructors will be called when the stack unwind when the exception is thrown in the constructor, and those destructors will deallocate the allocated memory.

    int main(){
        base *temp = new base();
    }
    

    For ordinary memory allocation using (non-plcaement) new, memory allocated by the operator new is freed automatically if the constructor throws an exception. In terms of why bother freeing individual members (in response to comments to Mike B's answer), the automatic freeing only applies when an exception is thrown in a constructor of an object being new'ly allocated, not in other cases. Also, the memory that is freed is those allocated for the object members, not any memory you might have allocated say inside the constructor. i.e. It would free the memory for the member variables a, pint, objsomeclass, and psomeclass, but not the memory allocated from new someclass() and new int().

提交回复
热议问题