【问题标题】:Templates causing Segmentation Fault in c++在 C++ 中导致分段错误的模板
【发布时间】:2016-10-05 11:00:01
【问题描述】:

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

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();
}

队列中的某些字对象在调试器中显示为NULL,因此导致Seg-Fault。

【问题讨论】:

  • 我很确定在Command 构造函数中你打算写this-&gt;w = w; 等等......想想你实际写了什么。
  • @paddy:这不是 java,它应该在 c++ 中工作:stackoverflow.com/questions/268587/…。只要使用初始化列表。 (显然不是。)
  • 我并不是说这是好的 C++ 风格,但比起建议他们显然不理解的初始化程序列表,让他们思考使用该示例的区别更容易。

标签: c++ templates


【解决方案1】:

要解决问题,请更改

Command::Command(word *w, Method m){
   w = w;
   m = m;
}

Command::Command(word *w, Method m) : w(w), m(m){}

具体原因看Can I use identical names for fields and constructor parameters?

【讨论】:

  • 非常感谢,现在正在运行。没想到函数和构造函数参数会造成这样的麻烦,因为我习惯在java中像上面那样部署它们。
猜你喜欢
  • 2014-04-24
  • 2021-06-16
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多