简体   繁体   中英

Copy constructor calls destructor c++

I have a test class of my to make my own string functions. I have a problem with the copy destructor.

I have 2 strings: s1 and s2. I call the function s3 = s1 + s2;

It first calls the operator+ function and when it's finished it calls the destructor. Because of this the string object in the operator= function is empty. How can I fix this?

Destructor:

String::~String() {
  if (this->str)
    delete[] str;
  str = NULL;
  len = 0;
}

Copy Constructor:

String::String(const String& string) {
  this->len = string.len;
  if(string.str) {
    this->str = new char[string.len+1];
    strcpy(this->str,string.str);
  } else {
    this->str = 0;
  }
}

operator= :

String & String::operator= (const String& string) {
  if(this == & string)
    return *this;

  delete [] str;

  this->len = string.len;

  if(string.str) {
    this->str = new char[this->len];
    strcpy(this->str,string.str);
  } else {
    this->str = 0;      
  }

  return *this;
}

operator+ :

String& operator+(const String& string1 ,const String& string2)
{
  String s;

  s.len = string1.len + string2.len;
  s.str = new char[string1.len + string2.len+1];
  strcpy(s.str,string1.str);
  strcat(s.str,string2.str);

  return  s;
}

operator+ should not return a local variable by reference.

Change the return type of operator+ to String . Ie, make the signature:

String operator+( String const& lhs, String const& rhs )

You probably also want to write a "move constructor" for your String class: String( String&& other ) if you are writing your code in C++11.

A simple move constructor:

String::String( String&& other ): len(other.len), str(other.str) {
  other.len = 0;
  other.str = nullptr;
}

This isn't required, because the copy in the return statement of your operator+ will probably be "elided" by your compiler under non-trivial optimization levels, but still good practice.

It's calling the Destructor because String s is going out of scope in your operator+ overload. Your operator+ overload needs to be returning a copy instead of a reference.

Therefore you should change your operator+ to

String operator+(const String& string1, const String& string2)

Yeah i got your problem

The thing is when you are returning a reference to a temp object from + operator function and then you are assigning this to other object in main So here = overloaded function gets called in to which you are passing a reference to an object that no longer exists

So either you can return a copy from + operator function

or

you can pass a copy in the = overlaoded function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM