c++中导致分段错误的模板

Templates causing Segmentation Fault in c++

本文关键字:错误 分段 c++      更新时间:2023-10-16

下面的简单代码片段中有一个问题,即使使用调试器也无法发现。提前感谢您的帮助。

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){}

要了解确切的推理,请参见我可以为字段和构造函数参数使用相同的名称吗?