ошибку сегментации Я создал тип myType
вместе с набором операторов сравненияСТД :: установить <myType>
const bool operator< (const myType& a, const myType& b);
const bool operator> (const myType& a, const myType& b);
const bool operator==(const myType& a, const myType& b);
const bool operator!=(const myType& a, const myType& b);
const bool operator<=(const myType& a, const myType& b);
const bool operator>=(const myType& a, const myType& b);
, который, как таковой, работает достаточно хорошо. Также существует конструктор копирования для myType. Теперь я хочу, чтобы создать набор myTypes, но получить сбой:
#include <set>
...
namespace std;
...
myType a; // default constructor exists
set<myType> theObjects;
theObjects.insert(a); // <-- segfaults
Я понятия не имею, почему это происходит. Я был и у меня сложилось впечатление, что существования operator <
должно быть достаточно, чтобы использовать <set>
. Отладчик говорит мне, что segfault происходит в stl_iterator.h. Кодирование в этом месте гласит:
__normal_iterator
operator-(const difference_type& __n) const // <-- here is the
// instruction pointer
// when it crashes.
{ return __normal_iterator(_M_current - __n); }
Любые идеи кто-нибудь? myType имеет атрибут вектора типа, если это имеет значение. ОС - это Windows 7 Professional, компилятор g ++ из дистрибутива MinGW.
В случае, если кто может сделать что-то с ним, вот трассировки стека:
#0 77343242 ntdll!LdrLoadAlternateResourceModuleEx() (C:\Windows\system32\ntdll.dll:??)
#1 00000000 0x7718a4ef in ??() (??:??)
#2 77343080 ntdll!LdrLoadAlternateResourceModuleEx() (C:\Windows\system32\ntdll.dll:??)
#3 00000002 ??() (c:/mingw/bin/../lib/gcc/mingw32/4.5.2/include/c++/bits/stl_iterator.h:775)
#4 00000000 0x006d00c4 in ??() (??:??)
Ответ на комментарий: деструктор и назначение оператора существует, а, но, возможно, это помогает, если я их вывешу:
конструктор:
myType::myType {
this->init(); // assigns NULL to a pointer attribute
rep.push_back((unsigned short) 0); // rep ist the vector attribute
}
копия конструктора:
myType::myType(const myType::myType& u) : rep(u.rep) {
this->init(); // by intention
this->cleanLeadingZeroes(); // removes leading zero from rep, if any
}
оператор присваивания:
myType& myType::operator=(const myType& rhs) {
if (this == &rhs) return *this;
this->rep.clear();
this->rep = rhs.rep;
return *this;
}
деструктор:
myType::~myType() {
rep.clear();
if (this->pointerVar != NULL) delete this->pointerVar;
}
operator <
, отвечая на другой вопрос ...
const bool operator<(const myType& a, const myType& b) {
unsigned aNrBTs = a.size() - a.countLeadingZeroes(); // myType represents a big Int
unsigned bNrBTs = b.size() - b.countLeadingZeroes(); // here the representations
// are compared. size
// just returns rep.size()
if (aNrBTs < bNrBTs) return true;
if (aNrBTs > bNrBTs) return false;
for (int i = aNrBTs - 1; i >= 0; --i) {
if (a.get(i) < b.get(i)) return true; // get returns ith entry in
else if (a.get(i) > b.get(i)) return false; // vector
else continue;
}
return false;
}
функция инициализации:
void myType::init() {
this->pointerVar = NULL; // pointerVar is a pointer attribute of type myType *
}
чистые ведущие нули:
void myType::cleanLeadingZeroes() {
auto it = rep.rbegin();
while(it!= rep.rend()) {
if (*it != (unsigned short)0) break;
++it;
auto end = rep.end();
--end;
rep.erase(end);
}
if (this->rep.size() == 0) rep.push_back((unsigned short)0); // make sure vector
// contains one element
}
EDIT:
Ok спасибо всем, кто ответил или прокомментировал это сейчас. Я мог бы сузить это немного после вашего совета. Segfault возникает в конструкторе копирования, когда вектор копируется. Это происходит в stl_vector.h
, кодирование выглядит следующим образом:
size_type
capacity() const
{ return size_type(this->_M_impl._M_end_of_storage
- this->_M_impl._M_start); }
Здесь this->_M_impl._M_end_of_storage
является 0x0, а this->_M_impl._M_start
нет. Любые идеи, почему это может быть так, кто-нибудь?
ТИА
Томас
Как насчет того, чтобы показать нам определение 'myType'? Поскольку вы упомянули конструктор копирования, но не оператор деструктора или копирования, я подозреваю, что вы нарушаете [Правило три] (http://stackoverflow.com/q/4172722/636019) и наблюдаете за повреждением памяти. – ildjarn
Привет, спасибо, что указал. Я добавил детали к вопросу. – Thomas
Какое определение для 'myType :: operator <'? –