segmentation fault in overloading operator =
我刚刚在重载类FeatureRandomCounts的赋值运算符时遇到SEG错误,该类的指针成员是指向FeatureCount和大小为rhs的数组的rects。_dim,其其他日期成员是非指针:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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; } |
有人知道一些线索吗?谢谢和问候!
字母名称(P)calls operator=-,which is the function you are writing.Cue infinite returnion,stack overflow,crash.(p)(P)Also,if you used a STD::Vector rather than a c-style array,you probably would not need to implement operator=-(……).(p)
(P)As mentioned,you have infinite returnion;however,to add to that,here's a foolproof way to implement op=:(p)字母名称(P)write a correct copy ctor and swap,and exception safety and all edge cases are handled for you!(p)(P)The copy parameter is passed by value and then changed.Any resources which the current instance must destroy are handled when copy is destroyed.1 This follows current recommendations and handles self-assignment cleanly.(p)字母名称(P)Notice it works with either manually managed members(p)or raii/sbrm-style members(s).(p)
字母名称(P)This is definitively not the way to do it.You call EDOCX1 penographic 4 original returnively,not calling the built in assignment operator.一个接一个的变量。Don't be Lazy.(p)
(P)The following line:(p)字母名称(P)我会打电话给你的EDOCX1音标0-音标函数结果在一个斯塔克Overflow。(p)(P)You should probably replace it with straight-forward assignments of the various member fields.(p)(P)As Neil said,using some thing like EDOCX1 commercial 1 will remove much of the responsibility away from your code.如果为Whatever Reason You can't or don't want to use EDOCX1 English 1,you might also want to consider using the'swap idiom'for your assignment operator.This will make the function exception safe(if the allocation of the memory for EDOCX1 universal 3.Array fails and throws an exception,the original object that's being assigned to will be left unchanged).Something like the following:(p)字母名称(P)Now your assignment can look like:(p)字母名称(P)注意,你需要一个物业copy constructor for this to work,但给大三规则你总是需要一个物业copy ctor。(p)