Search code examples
c++memory-managementdelete-operator

Am I deleting this properly?


I have some struct:

struct A
{
 const char* name_;
 A* left_;
 A* right_;
 A(const char* name):name_(name),
      left_(nullptr),
      right_(nullptr){}
 A(const A&);
 //A(const A*);//ToDo
 A& operator=(const A&);
 ~A()
 {
  /*ToDo*/
 };
};
/*Just to compile*/
A& A::operator=(const A& pattern)
{

 //check for self-assignment
 if (this != &pattern) 
 {
  void* p = new char[sizeof(A)];
 }
 return *this;
}

A::A(const A& pat)
{
 void* p = new char[sizeof(A)];
 A* tmp = new (p) A("tmp");
 tmp->~A();
 delete tmp;//I WONDER IF HERE I SHOULD USE DIFFERENT delete[]?
}

int _tmain(int argc, _TCHAR* argv[])
{
 A a("a");
 A b = a;
 cin.get();
 return 0;
}

I know this is far from ideal and far from finished. But I would like to know if I'm deleting my memory in the proper way (please don't tell me how to do it properly. I'm trying to figure it out myself).

This is the link to different question which is really important to me.


Solution

  • void* p = new char[sizeof(A)];
    A* tmp = new (p) A("tmp");
    tmp->~A();
    delete tmp;//I WONDER IF HERE I SHOULD USE DIFFERENT delete[]?
    

    No. You have already called the destructor so it is not correct to call delete which will cause another destructor call. You only need to free the memory. e.g.

    delete[] static_cast<char*>(p);
    

    If you are allocating raw memory for use with placement new it is more conventional to directly use an allocation function. e.g.

    void* p = ::operator new[](sizeof(A));
    A* tmp = new (p) A("tmp");
    tmp->~A();
    ::operator delete[](p);
    

    Consider doing something simpler, though. This block could be replaced with a single local variable which would be more robust.

    A tmp("tmp");