【问题标题】:Segfault when using pointer to class with unordered_map as member使用指向具有 unordered_map 作为成员的类的指针时出现段错误
【发布时间】:2016-08-25 09:39:39
【问题描述】:

我正在尝试实现我自己的类,它有一个 unordered_map 作为成员。现在奇怪的是,当我在使用指向我的类的指针时调用成员函数时出现分段错误,而当我不使用指针时一切都很好。

我附上了一个重现该问题的最小工作示例。我使用 Ubuntu 14.04 和 gcc 版本 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3),并使用g++ -std=c++11 TestClass.cc 编译了我的代码。你能告诉我有什么问题吗?

非常感谢!

TestClass.h:

#include <unordered_map>
#include <vector>
#include <iostream>

using namespace std;


// payload class, which is stored in the container class (see below)
class TestFunction {
  public:
    void setTestFunction(vector<double> func) {
      function = func;
    }
    void resize(vector<double> func) {
      function.resize(func.size());
    }
  private:
    vector<double> function;
};

// main class, which has an unordered map as member. I want to store objects of the second class (see above) in it
class TestContainer {
public:
  void setContainer(int index, TestFunction function) {
   cout << "Trying to fill container" << endl;
   m_container[index]=function; // <---------------- This line causes a segfault, if the member function is used on a pointer
   cout << "Done!" << endl;
  }
private:
  unordered_map<int,TestFunction> m_container;
};

主程序TestClass.cc:

#include <TestClass.h>

int main(void) {
  //define two objects, one is of type TestContainer, the other one is a pointer to a TestContainer
  TestContainer testcontainer1, *testcontainer2;

  // initialize a test function for use as payload
  TestFunction  testfunction;
  vector<double> testvector = {0.1,0.2,0.3};

  // prepare the payload object
  cout << "Setting test function" << endl;
  testfunction.resize(testvector);
  testfunction.setTestFunction(testvector);

  // fill the payload into testcontainer1, which works fine
  cout << "Filling test container 1 (normal)" << endl;
  testcontainer1.setContainer(1,testfunction);

  // fill the same payload into testcontainer2 (the pointer), which gives a segfault
  cout << "Filling test container 2 (pointer)" << endl;
  testcontainer2->setContainer(1,testfunction);

  return 0;
}

【问题讨论】:

    标签: c++11 pointers unordered-map


    【解决方案1】:

    您没有初始化 testcontainer2。这就是为什么您在尝试使用它时会遇到 seg 错误。

    【讨论】:

    • 我被它成功调用成员函数并在那里崩溃的事实分心了。但替换 'TestContainer *testcontainer2;'通过'TestContainer *testcontainer2 = new TestContainer();'成功了!
    • 实际上,未初始化的指针具有未指定的值。不保证为空。
    • 谢谢。更新了答案以反映这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2015-09-10
    • 2021-12-03
    • 2018-03-24
    • 1970-01-01
    • 2013-11-18
    相关资源
    最近更新 更多