Copy constructor calls destructor c++

安稳与你 提交于 2019-12-24 09:18:27

问题


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;
}

回答1:


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.




回答2:


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)



回答3:


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



来源:https://stackoverflow.com/questions/16177157/copy-constructor-calls-destructor-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!