c++中导致分段错误的模板
Templates causing Segmentation Fault in c++
下面的简单代码片段中有一个问题,即使使用调试器也无法发现。提前感谢您的帮助。
Command.h
class word{
private : static int next_word;
private : int word_id;
public : word();
public : void grabIt();
public : void raiseIt();
public : void putItDown();
};
class Command{
public : typedef void(word::*Method)();
private : word* w;
private : Method m;
public : Command(word *w, Method m);
public : void execute();
};
template<typename T>
class Queue{
private : enum{
SIZE=9
};
private : T* commandArray[SIZE];
private : int m_added = 0, m_removed = 0;
public : void enqueue(T* t){
commandArray[m_added] = t;
m_added = (m_added + 1) % SIZE;
}
public : T* dequeue(){
int temp = m_removed;
m_removed = (m_removed + 1) % SIZE;
return commandArray[temp];
}
};
Command.cpp
int word::next_word = 0;
word::word(){
this->word_id = next_word++;
}
void word::grabIt(){
std::cout << "Grabbed it" << std::endl;
}
void word::raiseIt(){
std::cout << "Raised it" << std::endl;
}
void word::putItDown(){
std::cout << "Put it down" << std::endl;
}
Command::Command(word *w, Method m){
w = w;
m = m;
}
void Command::execute(){
(w->*m)(); // -------------->>>>> Causing Seg-Fault
}
Main.cpp
Queue<Command> queue;
Command *commandArray[9];
Command command1(new word, &word::grabIt); commandArray[0] = &command1;
Command command2(new word, &word::raiseIt); commandArray[1] = &command2;
Command command3(new word, &word::putItDown); commandArray[2] = &command3;
Command command4(new word, &word::grabIt); commandArray[3] = &command4;
Command command5(new word, &word::raiseIt); commandArray[4] = &command5;
Command command6(new word, &word::putItDown); commandArray[5] = &command6;
Command command7(new word, &word::grabIt); commandArray[6] = &command7;
Command command8(new word, &word::raiseIt); commandArray[7] = &command8;
Command command9(new word, &word::putItDown); commandArray[8] = &command9;
for( int i=0 ; i < 9; i++){
queue.enqueue(commandArray[i]);
}
for( int i=2 ; i < 6 ; i++){
queue.dequeue()->execute();
}
队列中的一些word对象在调试器中显示为NULL,从而导致Seg-Fault。
要解决这个问题,请更改
Command::Command(word *w, Method m){
w = w;
m = m;
}
Command::Command(word *w, Method m) : w(w), m(m){}
要了解确切的推理,请参见我可以为字段和构造函数参数使用相同的名称吗?
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)