C++类对象的浅拷贝

在未定义显示拷贝构造函数的情况下,系统会调用默认的拷贝函数——即浅拷贝,它能够完成成员的一一复制。
在某些状况下,类内成员变量需要动态开辟堆内存,如果实行位拷贝,也就是把对象里的值完全复制给另一个对象,如A=B。这时,如果B中有一个成员变量指针已经申请了内存,那A中的那个成员变量也指向同一块内存。这就出现了问题:当B把内存释放了(如:析构),这时A内的指针就是野指针了,出现运行错误。

mystring.h

    #ifndef MYSTRING_H
    #define MYSTRING_H
   
    class mystring{
    private:
        char *s;
    public:
        mystring();
        mystring(const char *s);
        ~mystring();
        char *get_s();
        void set_s(const char *s);
    };
   
    #endif // MYSTRING_H

mystring.cpp

    #include <iostream>
    #include <string.h>
    #include "mystring.h"
   
    using namespace std;
   
    mystring::mystring():s(NULL){
    }
   
    mystring::mystring(const char *s){
        int len =strlen(s);
        this->s = new char[len+1];
        strcpy(this->s,s);
        this->s[len] = 0;
    }
   
    mystring::~mystring(){
        delete []s;
    }
   
    char *mystring::get_s()
    {
        printf("s Memory address is %p\n",&this->s);
        return s;
    }
   
    void mystring::set_s(const char *s){
        strcpy(this->s,s);
    }

main.cpp

    #include <iostream>
    #include <mystring.h>
    
    using namespace std;
    
    int main(){
        char *name = "wunanhui";
        mystring str1(name);
        mystring str2 = str1;
        cout << "1" << str1.get_s() << endl;
        cout << "2" << str2.get_s() << endl;
        str1.set_s("wuchanzhu1");
        str2.set_s("wuchanzhu2");
        cout << "3" << str1.get_s() << endl;
        cout << "4" << str2.get_s() << endl;
        return 0;
    }

结果

    s Memory address is 0028fea8
    1wunanhui
    s Memory address is 0028fea4
    2wunanhui
    s Memory address is 0028fea8
    3wuchanzhu2
    s Memory address is 0028fea4
    4wuchanzhu2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值