临时变量被重载的 + 和 += 运算符破坏

Temporary variable destroyed with overloaded + and += operator

我遇到了段错误,因为我相信我的临时变量在操作员使用完它之前就被销毁了(释放分配的内存)。这是我主要的代码:

int main(int argc, char *argv[])
{
  Bcd b1 = Bcd(100), b2 = Bcd(20), b3 = Bcd(50);
  b3 += b1 + b2;
  return 0;
}

我在析构函数中放了一条打印语句,输出结果如下:

sum
destroying 120
sum
segmentation fault

我不明白为什么会这样。看来临时变量b1+b2在sum第二次使用之前就被销毁了。临时变量 b1+b2 不应该在 main 中该行结束之前有效吗?我是否错误地实现了运算符重载函数,或者我的代码是否存在其他我没有考虑到的问题?

我的自定义class定义如下:

class Bcd
{
 public:
  Bcd();
  Bcd(const char* num);
  Bcd(const Bcd &num);
  Bcd(const int num);
  ~Bcd();
  int getLength() const;
  Bcd& operator=(const Bcd &rhs);
  Bcd& operator+=(const Bcd &rhs);
  const Bcd& operator +(const Bcd &rhs) const;
  std::string toString() const;
private:
  //takes a character and places is at number[index]. If that index does 
  //not exist, allocates memory for that number and then sets number[index].
  void modifyNumber(char num, int index);
  char* number;
  int length;
  int size;
};

.c 文件的重要部分在这里:

Bcd& Bcd::operator +=(const Bcd &rhs){
  int minSize, i;
  char result[2] = {0};
  printf("sum\n");
  if(this->getLength() < rhs.getLength())
    minSize = this->getLength();
  else
    minSize = rhs.getLength();

  for(i = 0; i < minSize; i++) //SEGFAULT from accessing rhs.number[0]
      this->modifyNumber(this->number[i] + rhs.number[i], i);

  if(this->getLength() < rhs.getLength()){
      for(;i < rhs.getLength(); i++)
          this->modifyNumber(rhs.number[i], i); 
    }
  else{
      for(;i < this->getLength(); i++)
          this->modifyNumber(this->number[i], i);
    }
  return *this;
}

const Bcd& Bcd::operator +(const Bcd &rhs) const
{
  return Bcd(*this) += rhs;
}

Bcd::Bcd(const Bcd &num)
{
  length = num.length;
  size = num.size;
  //allocate memory for number
  number = new char[length];
  for(int i = 0; i < length; i++)
      number[i] = num.number[i];
}

事情本该如此。可能更正确的说法是它不是临时的 b1 + b2 被破坏,它是临时的 Bcd(*this) += rhs 在你的二进制 + 实现中被破坏。

您对 +

的实施
const Bcd& Bcd::operator +(const Bcd &rhs) const
{
  return Bcd(*this) += rhs;
}

尝试 return 绑定到临时对象的引用。在函数退出之前临时对象被销毁,引用仍然挂起。调用者收到一个 "dead" 引用。行为未定义。

不是临时文件的生命周期通过附加到它的引用而延长的上下文之一。

您不能 return 从您的二进制 + 引用。您根本没有任何 return 的参考。相反,return by value

Bcd Bcd::operator +(const Bcd &rhs) const
{
  return Bcd(*this) += rhs;
}

此实施确实 return 将用作 b1 + b2 的临时文件。而且那个临时的不会被过早的销毁。

一个问题是 operator+ 应该 return 对象的副本,而不是引用。我认为您的代码创建了一个临时文件并return引用了它,这是一个很大的问题。

你的编译器应该警告过你。如果使用 GCC,则每次都使用 -W -Wall。会有很大帮助。

这很奇怪。我用我的 GCC 对此进行了测试,如果我使用 -O2 或 -O3 优化进行编译,我只会收到警告。