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.
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, . .
new
void* p = ::operator new[](sizeof(A)); A* tmp = new (p) A("tmp"); tmp->~A(); ::operator delete[](p);
, - . , .
A tmp("tmp");
p = new[…], delete[] p [1] .
p = new[…]
delete[] p
tmp .
tmp
( new , new char[sizeof(A)], .)
new char[sizeof(A)]
[1]: p char*. p char* delete[].
p
char*
delete[]
, , A, A* p = new A("tmp");. . delete p; . .
A
A* p = new A("tmp");
delete p;
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("a");
A::A(const std::string& name) { //Do stuff }
, () :
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 *
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.
std::map
std::list
Source: https://habr.com/ru/post/1740051/More articles:setting file name in NSPrintInfo - objective-cExport jar resources via website - javaЗначение текстового поля изменено - c#Python calculation Ephem / Datetime - pythonDoes Visual Studio 2008 compile anything in a C ++ file? - c ++Стрелки обобщения - oopUnable to connect to socket on different networks - javaPHP: how to find the most used array key? - arraysОшибки разработки Fluid в ie7 - htmlSplitting PDF to png - ruby-on-railsAll Articles