狂自私

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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   狂自私  阅读(43)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2019-04-29 关于桌面图标
2019-04-29 python 使用多进程打开多个cmd窗口,并在子进程结束之后关闭cmd窗口
点击右上角即可分享
微信分享提示