2016-08-25 1 views
0

멤버로 unordered_map이있는 클래스를 구현하려고합니다. 이제는 이상한 점은 클래스를 가리키는 포인터를 사용할 때 멤버 함수를 호출 할 때 세분화 오류가 발생한다는 것입니다. 포인터를 사용하지 않아도 괜찮습니다.멤버로 unordered_map 클래스의 포인터를 사용할 때 Segfault

문제를 재현하는 최소 작업 예제를 첨부했습니다. 나는 gcc 버전 4.8.4 (Ubuntu 4.8.4-2ubuntu1 ~ 14.04.3)로 우분투 14.04를 사용하고 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; 
} 

답변

1

당신은 testcontainer2를 초기화하지 않았다. 그래서 사용하려고하면 seg 오류가 발생합니다.

+0

멤버 함수를 성공적으로 호출하고 거기에 충돌한다는 사실에 정신이 산만했습니다. 하지만 'TestContainer * testcontainer2;' 'TestContainer * testcontainer2 = new TestContainer();'에 의해 트릭을 했어! – vueltaconicarus

+0

실제로 초기화되지 않은 포인터는 지정되지 않은 값을 갖습니다. null이되는 것은 보증되지 않습니다. – user2079303

+0

감사합니다. 이를 반영하기 위해 답변을 업데이트했습니다. –

관련 문제