Am I deleting this correctly?

I have a structure:

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 that this is far from ideal and far from finished. But I would like to know if I am deleting my memory correctly (please do not tell me how to do it properly. I am trying to figure it out myself).

This is a link to another question that really matters to me.

+3
source share
5 answers
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 wrong to call a delete that will cause another call to the destructor. You need to free memory. eg.

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

new, . .

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

, - . , .

A tmp("tmp");
+4

p = new[…], delete[] p [1] .

tmp .

( new , new char[sizeof(A)], .)

[1]: p char*. p char* delete[].

+2

, , A, A* p = new A("tmp");. . delete p; . .

0
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[]?
}

, delete [], []. , , ( - ), , , , .

(~ A ) , , . , , , , .

. , : A a("a");, :

A::A(const std::string& name)
{
   //Do stuff
}
0

, () :

class Node
{
  char * name_;
  Node * p_left;
  Node * p_right;

  Node(const char * new_name)
  : name_(NULL), p_left(NULL), p_right(NULL)
  {
    size_t size = strlen(new_name);
    name_ = new char [size + 1]; // + 1 for terminating null
  }
  ~Node()
  {
     delete[] name_;
  }
};

:

  • std::string char * .
  • Move links to the base class (it is preferable to use a template for the Node data section.}

The base class will allow you to adapt node to various data types:

struct Node
{
    Node * p_left;
    Node * p_right;
};

struct Name_Node
: public Node
{
  std::string name;
};

struct Integer_Node
: public Node
{
  int value;
};

OTOH, you can use std::mapor std::listafter this exercise.

0
source

Source: https://habr.com/ru/post/1740051/


All Articles