为什么我不能在方法isCaseSensitive
中更改对象的assocTab::swap()
值? isCaseSensitive
字段在assocTab()
构造函数内初始化。
Valgrind输出:
==13666== Conditional jump or move depends on uninitialised value(s)
==13666== at 0x401341: assocTab::setCaseSensitivity(bool) (assoctable.cpp:117)
==13666== by 0x401157: assocTab::swap(assocTab&) (assoctable.cpp:68)
==13666== by 0x4011C3: assocTab::operator=(assocTab const&) (assoctable.cpp:77)
==13666== by 0x4015FE: main (main.cpp:21)
==13666==
我的方法和isCaseSensitive
所属的简化类:
class assocTab{
private:
struct node{
node* next;
char* key;
int val;
};
node* head;
bool isCaseSensitive;
void clear();
void swap(assocTab& l);
public:
void setCaseSensitivity(bool);
bool getCaseSensitivity() const;
};
assocTab::assocTab(){
head = NULL;
setCaseSensitivity(true);
}
assocTab::assocTab(const assocTab& l){
node *src, **dst;
head = NULL;
src = l.head;
dst = &head;
try{
while(src){
*dst = new node (*src);
src = src->next;
dst = &((*dst)->next);
}
}catch(...){
clear();
throw;
};
}
void assocTab::swap(assocTab& l){
bool swpCS = getCaseSensitivity();
bool swpCS2 = l.getCaseSensitivity();
l.setCaseSensitivity(swpCS);
setCaseSensitivity(swpCS2); //line 68
std::swap(l.head, head);
}
void assocTab::setCaseSensitivity(bool isCS){
if(isCS) //line 117
isCaseSensitive = true;
else
isCaseSensitive = false;
}
bool assocTab::getCaseSensitivity() const{
return isCaseSensitive;
}
assocTab& assocTab::operator= (const assocTab& l){
if (&l == this)
return *this;
assocTab t(l);
swap(t);
return *this;
}
答案 0 :(得分:0)
您的复制构造函数似乎没有复制isCaseSensitive
的值。因此,当调用operator+()
方法并使用复制构造函数创建本地副本时,当您使用本地副本调用swap时,该值仍未初始化。