模板类的析构函数

时间:2017-12-14 20:59:36

标签: c++ c++11

我有模板类。其中一个参数是char*std::string。所以我必须删除char*,并删除t delete std :: string`。我不知道该怎么做。

template <typename T>
class Discipline
{
public:
    unsigned int getLectureHours() const { return lecture_hours; }

    unsigned int getTotalHours() const { return total_hours; }

    unsigned int getPracticalHours() const { return practical_hours; }

    unsigned int getSelfHours() const { return self_hours; }

    T getName() const { return name; }

    Date& getDate() const { return date; }

    Discipline() : date(1,1,2000), name("Math"), total_hours(10), lecture_hours(4), practical_hours(4), self_hours(2) {}

    Discipline(Date* tdate, T& tname, int& t1, int& t2, int& t3) : date(*tdate), name(tname), total_hours(t1), lecture_hours(t2), practical_hours(t3), self_hours(t1-t2-t3){}

    Discipline(const Discipline<T>& other)
    {
        *this = other;
        name = "def";
    }

    Discipline<char*>& operator=(const Discipline<char*>& param)
    {
        if (this != &param)
        {
            this->name = new char[strlen(param.name)+1];
            strcpy(this->name, param.name);
            this->date = param.date;
            this->total_hours = param.total_hours;
            this->lecture_hours = param.lecture_hours;
            this->self_hours = param.self_hours;
            this->practical_hours = param.practical_hours;
        }
        return *this;
    }

    Discipline<std::string>& operator=(const Discipline<std::string>& param)
    {
        if (this != &param)
        {
            // this->name = "";
            // this->name += "def";
            this->date = param.date;
            this->total_hours = param.total_hours;
            this->lecture_hours = param.lecture_hours;
            this->self_hours = param.self_hours;
            this->practical_hours = param.practical_hours;
        }
        return *this;
    }

    ~Discipline<char*>() {  delete[] name; }

private:
    Date date;
    T name;
    unsigned int total_hours;
    unsigned int lecture_hours;
    unsigned int practical_hours;
    unsigned int self_hours;
};

2 个答案:

答案 0 :(得分:3)

有明确的专业化。在实现中,您可以像

一样
template<>
Discipline<string>::~Discipline(){}

template<>
Discipline<char*>::~Discipline(){
    delete[] name;
}

这甚至可以灵活地完成:

template<class T>
Discipline<T>::~Discipline(){}

template<>
Discipline<char*>::~Discipline(){
    delete[] name;
}

如果你打算在将来添加更多的特化,那么这个变体会在类char*上调用delete而在析构函数中不执行任何操作。

您可能需要阅读http://en.cppreference.com/w/cpp/language/template_specialization

(只是回答所述的问题。当然,antred的评论是实际的解决方案。)

答案 1 :(得分:0)

一个变体是添加一个简单的静态方法,比如DeleteTheString,带有两个参数重载。然后你只需用你的模板化类型值调用,让编译器决定。

另一种变体是将char *包装在unique_ptr []中,因此它会自行删除。您可以通过让一个小适配器类SafeStore具有成员typedef std::string as来动态地执行此操作,而SafeStore具有typedef std::unique_ptr<char[]> as