【问题标题】:Copy constructor calls destructor c++复制构造函数调用析构函数 c++
【发布时间】:2013-04-17 03:05:09
【问题描述】:

我有一个测试类来制作我自己的字符串函数。我对复制析构函数有疑问。

我有 2 个字符串:s1 和 s2。 我调用函数 s3 = s1 + s2;

它首先调用 operator+ 函数,完成后调用析构函数。因此,operator= 函数中的字符串对象为空。我该如何解决这个问题?

析构函数:

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

复制构造函数:

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

【问题讨论】:

    标签: c++ destructor operator-keyword copy-constructor


    【解决方案1】:

    operator+ 不应通过引用返回局部变量。

    operator+的返回类型改为String。即,进行签名:

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

    如果您使用 C++11 编写代码,您可能还想为您的 String 类编写一个“移动构造函数”:String( String&& other )

    一个简单的移动构造函数:

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

    这不是必需的,因为您的 operator+ 的 return 语句中的副本可能会被您的编译器在非平凡的优化级别下“删除”,但仍然是一种很好的做法。

    【讨论】:

      【解决方案2】:

      它正在调用析构函数,因为String s 超出了您的 operator+ 重载的范围。您的 operator+ 重载需要返回副本而不是引用。

      因此您应该将您的 operator+ 更改为

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

      【讨论】:

        【解决方案3】:

        是的,我有你的问题

        问题是当您从 + 运算符函数返回对临时对象的引用,然后将其分配给 main 中的其他对象所以这里 = 重载函数被调用,您正在向其中传递对对象的引用已经不存在了

        所以你可以从 + 运算符函数返回一个副本

        你可以在=overlaoded函数中传递一个副本

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-02-08
          • 2018-10-17
          • 2011-07-17
          • 1970-01-01
          • 2011-04-16
          • 2021-07-19
          • 1970-01-01
          相关资源
          最近更新 更多