【笔试题】深拷贝与浅拷贝(一)

今天做了道笔试题,是一道改错题,错误隐藏的还蛮深,但要是想到深拷贝和浅拷贝,就容易多了。
题目:

 #include   <vector>  
 #include   <iostream>  
 using   namespace   std;    
 class   CDemo  
 {  
 public:  
          CDemo()   :   str(NULL)   {};  
         ~CDemo()   {   if   (str)   delete   []   str;}  
          char   *str;  
 };  
void   main   (void)  
 {  
          CDemo   d1;  
          d1.str   =   new   char[32];  
          strcpy   (d1.str,   "trend   micro");  
          cout   <<   d1.str;  
          vector<CDemo>   *a1   =   new   vector<CDemo>();  
          a1->push_back(d1);  
          delete   a1;  
 }    

哪里有问题?
a1->push_back(d1);
这句调用了默认的拷贝构造函数,是浅拷贝,所以有两个str指针指向同一块内存,析构函数调用两次,第二次delete [] str;引起程序崩溃 。
改错:
应自定义拷贝构造函数

#include <vector>
#include <iostream>
#include <string.h>
using namespace std;

class CDemo
{
    public:
        CDemo(): str(NULL){

        }
        CDemo(const CDemo& other): str(NULL)
        {
            if(other.str)
            {
                str = new char[strlen(other.str) + 1];
                strcpy(str, other.str);
            }
        }

        CDemo& operator=(const CDemo& other)
        {
            if(this == &other)
            {
                return *this;
            }

            delete [] str;
            str = 0;
            if(other.str){
                str = new char [strlen(other.str) + 1];
                strcpy(str, other.str);
            }
            return *this;
        }

        ~CDemo(){
            if(str)
            {
                delete [] str;
            }
        }


        char *str;
};

int main(void)
{
    CDemo d1;
    d1.str = new char[32];
    strcpy(d1.str, "trend micro");
    cout << d1.str;
    vector<CDemo> *a1 = new vector<CDemo> 


();
    a1->push_back(d1);
    delete a1;
    return 0;
}

总结一下,遇到指针赋值和拷贝的操作,一定要联想到深拷贝和浅拷贝的问题!!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值