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).
这篇关于重载运算符中的分段错误 =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:重载运算符中的分段错误 =


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01