重载运算符中的分段错误 = [英] segmentation fault in overloading operator =

查看:24
本文介绍了重载运算符中的分段错误 =的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在重载类 FeatureRandomCounts 的赋值运算符时遇到了一个段错误,该类具有 _rects 作为其指针成员,指向 FeatureCount 和大小为 rhs._dim 的数组,并且其其他日期成员是非指针:

I just got a seg fault in overloading the assignment operator for a class FeatureRandomCounts, which has _rects as its pointer member pointing to an array of FeatureCount and size rhs._dim, and whose other date members are non-pointers:

FeatureRandomCounts &  FeatureRandomCounts::operator=(const FeatureRandomCounts &rhs)  
{  
  if (_rects) delete [] _rects;  

  *this = rhs;  // segment fault

  _rects = new FeatureCount [rhs._dim];  
  for (int i = 0; i < rhs._dim; i++)  
  {  
    _rects[i]=rhs._rects[i];  
  }  

  return *this;    
}

有人知道吗?谢谢和问候!

Does someone have some clue? Thanks and regards!

推荐答案

如前所述,你有无限递归;但是,除此之外,这是实现 op= 的一种万无一失的方法:

As mentioned, you have infinite recursion; however, to add to that, here's a foolproof way to implement op=:

struct T {
  T(T const& other);
  T& operator=(T copy) {
    swap(*this, copy);
    return *this;
  }
  friend void swap(T& a, T& b);
};

编写正确的复制ctor和swap,异常安全和所有边缘情况都为你处理!

Write a correct copy ctor and swap, and exception safety and all edge cases are handled for you!

copy 参数是按值传递 然后改变的.当前实例必须销毁的任何资源都会在 copy 被销毁时处理.这遵循 当前建议 并处理 自我分配干净.

The copy parameter is passed by value and then changed. Any resources which the current instance must destroy are handled when copy is destroyed. This follows current recommendations and handles self-assignment cleanly.

#include <algorithm>
#include <iostream>

struct ConcreteExample {
  int* p;
  std::string s;

  ConcreteExample(int n, char const* s) : p(new int(n)), s(s) {}
  ConcreteExample(ConcreteExample const& other)
  : p(new int(*other.p)), s(other.s) {}
  ~ConcreteExample() { delete p; }

  ConcreteExample& operator=(ConcreteExample copy) {
    swap(*this, copy);
    return *this;
  }

  friend void swap(ConcreteExample& a, ConcreteExample& b) {
    using std::swap;
    //using boost::swap; // if available
    swap(a.p, b.p); // uses ADL (when p has a different type), the whole reason
    swap(a.s, b.s); // this 'method' is not really a member (so it can be used
                    // the same way)
  }
};

int main() {
  ConcreteExample a (3, "a"), b (5, "b");
  std::cout << a.s << *a.p << ' ' << b.s << *b.p << '
';
  a = b;
  std::cout << a.s << *a.p << ' ' << b.s << *b.p << '
';
  return 0;
}

请注意,它适用于手动管理的成员 (p) 或 RAII/SBRM 样式的成员 (s).

Notice it works with either manually managed members (p) or RAII/SBRM-style members (s).

这篇关于重载运算符中的分段错误 =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆