狂自私

导航

C++ 编程好习惯

声明变量的时候进行初始化:

int a{};
double b{};
char* p{};
bool c{};
char cc[10]{};

手动释放空间后,将该指针值置为nullptr

这是为了防止重复释放空间,尤其在类继承的情况下,析构函数释放空间之后,应该要将指针置为nullptr:

class baseDMA
{
public:
    baseDMA(const char* l = "null", int r = 0);
    baseDMA(const baseDMA& rs);
    virtual ~baseDMA();
    baseDMA& operator=(const baseDMA& rs) {
        if (this == &rs) {
            return * this;
        }
        this->~baseDMA();        //调用析构函数

        size_t strLen = std::strlen(rs.label);
        this->label = new char[strLen + 1];
        strncpy_s(this->label, strLen + 1, rs.label, strLen);
        this->rating = rs.rating;
        
        return *this;
    }
    friend std::ostream& operator<<(std::ostream& os, const baseDMA& rs);
private:
    char* label{};
    int rating{};
};
class hasDMA:public baseDMA
{
public:
    hasDMA(const char* s = "none", const char* l = "null", int r = 0);
    hasDMA(const hasDMA& rs);
    hasDMA& operator=(const hasDMA& rs){
        if (this == &rs) {
            return *this;
        }
        this->~hasDMA();    //调用析构函数,将派生类和包含在派生类的基类的空间都释放掉

        //这里就会报错,因为基类的赋值运算符重载也会去释放空间。
        //假若基类的析构函数没有将指针置为nullptr
        baseDMA::operator=(rs);    

        size_t str_len = std::strlen(rs.style);
        this->style = new char[str_len + 1]{};
        strncpy_s(this->style, str_len + 1, rs.style, str_len);

        return *this;
    }
    friend std::ostream& operator<<(std::ostream& os, const hasDMA& rs);
    ~hasDMA();

private:
    char* style{};
};

当然,也可以不去调用析构函数,手动编码去释放空间。

 不是从同一个vector等分配出来的迭代器不要比较,会报错迭代器不匹配,哪怕类型不一样,若是需要比较地址,那么使用data函数

 

posted on 2022-04-29 15:37  狂自私  阅读(36)  评论(0编辑  收藏  举报