Related Lists | Overload + operator | C ++

I am training my C ++ and I am trying to write a library that will represent the following number using linked lists:

999999999 * ([i = 0] Σ [999999999] 1,000,000,000 ^ i)

For example, if my number is 711381450277869054011 , it will be represented as follows:

711 * 1 000 000 000 ^ 2 + 381450277 * 1 000 000 000 ^ 1 + 869054011 > * 1 000 000 000 ^ 0

So, here is the structure of my LL and it functions:

typedef struct node* ll; struct node { unsigned int data; ll next; }; bool insert(ll&, unsigned int); // ... void copy(ll&, ll); void destroy(ll&); 

And here is my class of unsigned very long integers:

 class uli { public: uli(); ~uli(); // <<, >>, =, operators... uli& operator +=(const uli&); uli& operator +=(char*); const uli operator +(const uli&); private: ll head; }; uli::uli() { head = NULL; insert(head, 0); } uli::~uli() { destroy(head); } 
Operator

+ = works fine, and I use it to overload the + operator.

The problem is that I cannot get the operator + () method to return const uli without destroying it with the deconstructor before I use it.

 const uli uli::operator +(const uli& rarg) // rarg: right argument { uli larg; // left argument larg = *this; larg += rarg; return larg; } // returns an LL to somewhere ???? larg was destroyed. 

Now I can not do Z = X + Y;

+4
source share
1 answer

You need to follow the rule of three ,

If your class needs

  • copy constructor
  • assignment operator
  • or destructor

you will probably need all three of them.

Root Cause of your problems:
In your case, when you return an instance of the uli class by copying from the overloaded operator + , the implicit copy constructor created by the compiler is used and it makes a shallow copy of your pointers, so several pointers point to the same memory address and when one / some of them ( temporary objects) are destroyed, the indicated memory is freed through the destructor, and this leaves other pointers (dangling) indicating memory / content that do not exist.

Decision:
Follow rule 3 and create your own copy constructor to perform the Deep Copying of the pointers involved.

+6
source

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


All Articles