开发者

Calling member function of templated member

开发者 https://www.devze.com 2023-03-24 01:41 出处:网络
This program compiles fine but seg faults when running the value->getSmall in Period::display(). I\'m working on linux with g++. I\'ve provided a getSmall function for all the classes that may be u

This program compiles fine but seg faults when running the value->getSmall in Period::display(). I'm working on linux with g++. I've provided a getSmall function for all the classes that may be used as T. Just to be sure I added the debug lines and found that the segfault is caused when type of value ie T is Class* . I came across some FAQ which mentioned some problems like calling independent values in a templated context but I'm clueless about how to solve this.

using namespace std;
template <class T> //T is the class which has to be related & referenced to by period
class Period
{
    T value;    
public:

    void display()
    {
            cout<<setw(5)<<"| "<< value->getSmall() << "|";

                size_t len;  //for debug
                int s;        //for debug
                char* p=abi::__cxa_demangle(typeid(value).name(), 0, &len, &s);   //for debug
                cout<<setw(5)<<"| "<< p << "|";       //for debug
    }

};


class Class
{
    string name;
    timeTable<Teacher*> tt; //class timetable contains pointers to teachers
    vector<Teacher::teachTimePerClass> teachers; //set of all teachers teaching in a Class with corresponding total time

    //assigns a teacher to a period in a day
    bool assign(dayNames day,int periodNum,Teacher *teacher)
    {
        tt.assign(day,periodNum,teacher);       //assign the value in this Class's timetable
        teacher->assign(day,periodNum,this);    //update the teacher's timeTable
    }

public:
        static vector<Class*> Clas开发者_如何学运维ses; //dont forget to destory it at the end!!


    string getSmall()
    {
        return name;
    }
};
vector<Class*> Class::Classes;


You assume T to be a pointer, but never give it a value in Period.

That way you have an uninitialized pointer that is likely to segfault.


string getSmall()  // Class::getSmall()
{
  //return name;
}

If this is your real code than, your return statement is missing; which is an undefined behavior. Luckily you are getting a segmentation fault. This kind of bugs are difficult to trace. You should provide -Wall option while compiling with g++; it will suggest such kind of logical errors as warnings. See demo.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号