Wolf
Wolf

Reputation: 87

use += several times, changes are reversed c++

I have implemented a class vl_vector and a deriv class vl_string, which is pretty similar to STL vector (vl_string is for chars and handles the '\0' char). I have overloaded the += operator for char, char * and another vl_string. declarations:

  vl_string<StaticCapacity> operator+=(const vl_string<StaticCapacity>&vs);
  vl_string<StaticCapacity> operator+=(const char *str);
  vl_string<StaticCapacity> operator+=(char c);

Functions code:

template<size_t StaticCapacity>
vl_string<StaticCapacity> vl_string<StaticCapacity>::operator+= (const char *str)
{
  size_t len = strlen(str);
  //insert string before the '\0' char.
  vl_string<StaticCapacity>::insert(this->end() - 1, str, str + len);
  return *this;
}

template<size_t StaticCapacity>
vl_string<StaticCapacity> vl_string<StaticCapacity>::operator+= (const char c)
{
// push char to the end of string.
  this->push_back (c);
  return *this;
}

template<size_t StaticCapacity>
vl_string<StaticCapacity>
vl_string<StaticCapacity>::operator+= (const vl_string &vs)
{
  auto first = vs.cbegin();
  auto last = vs.cend() - 1; // to not include the '\0' char.
  // iterate over vl_string and insert each char to the end of string.
  while (first != last)
  {
    this->push_back (*first);
    first++;
  }
  return *this;
}

I'm trying to run the following code to check my program:

vl_string<> vl_str;
vl_string<> vl_str_to_add = "Never gonna";
(((vl_str += vl_str_to_add) += ' ') += "say goodbye") += '\n';
assert(vl_str.contains ("Never gonna say goodbye\n"));

I'm following the program in debugger, and everything seems to work. In the end I get a vl_string the contains the full desired string. But when the program reach the end of the line, it calls the destructor and deletes everything except the first operation (vl_str += vl_str_to_add). Tried several things but I'm pretty stuck, would love an explanation. thanks!

Upvotes: 1

Views: 77

Answers (1)

R Sahu
R Sahu

Reputation: 206707

The problem with your functions is that they return a copy of the object, not a reference.

Use

vl_string<StaticCapacity>& operator+=(const vl_string<StaticCapacity>&vs);
vl_string<StaticCapacity>& operator+=(const char *str);
vl_string<StaticCapacity>& operator+=(char c);
//                       ^^^ Reference return type.

Upvotes: 2

Related Questions