-1

Should I use delete overload or del() function or something else to deallocate class member?

class Field
{
private:
    size_t* square = new size_t[5];
public:
    void del()
    {
        delete[] square;
    }
    void operator delete (void* p)
    {
        delete[] reinterpret_cast<Field*>(p)->square;
    }
};
int main()
{
    Field f;

    delete &f; 
    //or
    f.del();
}
Vilkoxd
  • 15
  • 3
  • 11
    Neither. Please use a [destructor](http://en.cppreference.com/w/cpp/language/destructor). – François Andrieux Dec 13 '17 at 18:51
  • 5
    Don't use new or delete if you can avoid them. Use a `vector` – AndyG Dec 13 '17 at 18:52
  • [Are there any valid use cases to use new and delete, raw pointers or c-style arrays with modern C++?](https://stackoverflow.com/questions/46991224/are-there-any-valid-use-cases-to-use-new-and-delete-raw-pointers-or-c-style-arr) – user0042 Dec 13 '17 at 18:53

3 Answers3

6

You're looking for a destructor:

class Field
{
private:
    size_t* square = new size_t[5];
public:
    ~Field() { delete [] square; }
};

But learn the Rule of Zero and defer instead to a resource managing class:

class Field
{
private:
    std::unique_ptr<size_t[]> square;
public:
    Field() : square(new size_t[5]) { }
};

Which has the benefits of having move semantics already do the right thing, copy semantics already being disabled, and the destructor already managing your resources.

Barry
  • 286,269
  • 29
  • 621
  • 977
2

Should I use delete overload or del() function or something else to deallocate class member?

Neither.

Add a destructor and make sure to delete the memory in the destructor.

class Field
{
  private:
    size_t* square = new size_t[5];
  public:
    ~Field() { delete [] square; }
};

While at it, checkout the Rule of Three and follow the rule.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

First: Don't override the delete operator; this rarely makes sense. "Cleaning" up dependent objects, if necessary, is done in the destructor.

So you'd write

class Field {
   ...
   virtual ~Field() { delete[] square; }
   ...
}

Note that deleting a field (explicitly or implicitly) will trigger the destructor.

Second, call delete only on objects that you have previously created with new. Don't delete objects with automatic storage duration like you do with Field f; delete &f.

Third, avoid allocating objects with new if automatic storage duration is an option, too. So you'd overcome the complete issue if you wrote:

class Field
{
private:
    size_t square[5];
};

int main() {
    Field f;
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58