segmentation fault in overloading operator =(重载运算符中的分段错误 =)
问题描述
我刚刚在重载类 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).
这篇关于重载运算符中的分段错误 =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:重载运算符中的分段错误 =
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
