Search code examples
c++classoopmemorynew-operator

In C++, is there a pattern to make sure the new object pointer generated by the class static method will be deleted?


Is there a pattern to make sure the new object pointer generated by the class static method will be deleted?

I have a base class here.

// abstract class
class Expression{
    // method here ...
};

And a derived class here.

class Scaler: public Expression{
public:
    float value;

    Scaler(float _value) : value(_value){};

    static Expression* from(float value) {return new Scaler(value);}
    static Expression* zero(float value) {return from(0);}
}

the usage

Expression* num1 = Scaler::zero();
Expression* num2 = Scaler::from(69.0f);
//....
delete num1;  // <- is there a way to systematically delete those pointers?
delete num2;

Solution

  • You use std::unique_ptr:

    class Expression {
      public:
        virtual ~Expression() {} // <- was missing in your example!
    };
    class Scaler: public Expression{
      public:
        float value;
    
        Scaler(float _value) : value(_value){};
    
        static std::unique_ptr<Expression> from(float value) {
          return std::make_unique<Scale>(value);
        }
        static std::unique_ptr<Expression> zero() {return from(0);}
    };
    

    Crucially, an std::unique_ptr<Scale> object will implicitly convert to an std::unique_ptr<Expression> because Scale publicly inherits from Expression. See documentation above.

    You can use it just like your example:

    auto const num1 = Scaler::zero();
    auto const num2 = Scaler::from(69.0f);