There is such an overload of the operator ++ (postfix).

this ' s stores:

 s="first" length=5 

Here is the code itself:

 String& String::operator++(int i) { int n = this->length + 1; char* tmp = new char[n + 1]; for (int i = 0; i < this->length; i++) tmp[i] = this->s[i]; tmp[n - 1] = tmp[n - 2]; tmp[n] = '\0'; this->length = n; delete[] this->s; this->s = tmp; return *this; } 

On delete , a memory write error crashes.

  • What character should be added to the string by this operator if the source string is empty? From the code it is clear that you did not consider this. Your line will be empty again. - Vlad from Moscow
  • Note that the post-increment operator does not return a reference to the original object. - Vlad from Moscow
  • Thank you, I will consider. I haven’t done exception checking yet - Nikita

2 answers 2

Well, in general, the postfix increment of logic should return the old value (strings), which should actually be a copy. I no longer see errors in the code, but it can fly to delete because of how you selected s. If it points to read-only memory, then this is quite logical.

Those. if your initial value is assigned as this->s = "blabla" , the new char array is not created and your read-only string "blabla" is copied into it

  • Yes you are right. The error appeared in the operator >>. - Nikita
  • Here's what I got: 'istream & operator >> (istream & is, String & s) {char temp [256]; is >> temp; ss = new char [strlen (temp + 1)]; strcpy (ss, temp); s.length = strlen (ss); return is; } ' - Nikita
  • @ Nikita In this expression, new char [strlen (temp + 1)]; you incorrectly calculate the length of the string. I think you meant new char [strlen (temp) +1)]; - Vlad from Moscow
  • @VladfromMoscow Of course, this is just a slip of the pen) - Nikita

The error is due to an undefined program behavior. Apparently the pointer s does not contain a valid address or contains a memory address that was not allocated using the new operator .. Look for the cause in other members of the class where it is set or, conversely, the value s not set.

As for the operator itself, the post-increment operator usually returns a new temporary object, equal to the original one before its change, and changes the original one. That is, his ad looks generally like

 T operator ++( int ); 

or

 const T operator ++( int ); 

As for your String class, if the source string is empty, it does not change, because there are no characters in the string to use the last one as a placeholder character (Another approach is to use the space character as a placeholder).

With that said, the operator may look like this.

 String operator ++( int ) { String dsn( *this ); if ( this->length != 0 ) { size_t n = length + 1; char *tmp = new char[ n + 1 ]; std::memcpy( tmp, this->s, this->length ); tmp[ length ] = tmp[ length - 1 ]; tmp[n] = '\0'; delete [] s; this->s = tmp; this->length = n; } return dsn; }