zoukankan      html  css  js  c++  java
  • C++关于构造函数的深拷贝与浅拷贝

    首先拷贝构造函数的声明方法:

    类名::类名(const 类名&)

    1、浅拷贝的实现程序:

    #include "stdafx.h"
    #include <iostream>
    #include <cstring>
    using namespace std;
    class  Person
    {
    public:
    	//构造函数
    	Person(const char *name, double hei, double wei, 
    		int age0):height(hei),weight(wei),age(age0){
    		cout << "Person ctor called .
    ";
    		pName = new char[strlen(name) + 1];
    		strcpy(pName, name);
    	}
    	//析构函数
    	~Person(){
    		cout << "deleting pName";
    		delete[] pName;
    
    	}
    	//类Person的拷贝构造函数
    	Person(const Person &person){
    		cout << "Person copy ctor called";
    		pName = person.pName;
    		height = person.height;
    		weight = person.weight;
    		age = person.age;
    	}
    private:
    	char *pName;
    	double height;
    	double weight;
    	int age;
    };
    
    int main()
    {
    	Person p1("Leekin",175,185,25);
    	Person p2(p1);
    	return 0;
    }
    

      首先这个程序在VS2013上面编译不通过;是因为浅拷贝存在风险:非法操作内存,究其原因是因为“拷贝不充分”导致堆中的某一块内存被不同对象的指针属性同时指向,该内存不可避免的被释放多次,这是不应许。第一次被释放的空间已经属于操作系统,当在一次释放时那一片空间已经不属于程序了。

    以下是浅拷贝的内存模型:

    2、深拷贝可以避免由于浅拷贝带来的问题,即让拷贝函数做好充分的拷贝,程序如下:

    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    class  Person
    {
    public:
    	//构造函数
    	Person(const char *name, double hei, double wei, 
    		int age0):height(hei),weight(wei),age(age0){
    		cout << "Person ctor called .
    ";
    		pName = new char[strlen(name) + 1];
    		strcpy(pName, name);
    	}
    	//析构函数
    	~Person(){
    		cout << "deleting pName";
    		delete[] pName;
    
    	}
    	//类Person的拷贝构造函数
    	Person(const Person &person){
    		cout << "Person copy ctor called";
    		pName = person.pName;
    		height = person.height;
    		weight = person.weight;
    		age = person.age;
    		//深拷贝:重新申请一块内存
    		pName = new char[strlen(person.pName) + 1];
    		strcpy(pName, person.pName);
    	}
    private:
    	char *pName;
    	double height;
    	double weight;
    	int age;
    };
    
    int main()
    {
    	Person p1("Leekin",17.5,18.5,25);
    	Person p2(p1);
    	return 0;
    }
    

      深拷贝的内存模型:

  • 相关阅读:
    权限设计=功能权限+数据权限
    C# 自定义配置文件
    asp.net core 系列 2 启动类 Startup.CS
    asp.net core 系列 1 概述
    IOC : Unity 配置和使用
    Unity Ioc 依赖倒置及Untity AOP被动拦截/自动拦截
    webuploader-异步切片上传(暂不支持断点续传)及 下载方法!C#/.NET
    C# 构造基础返回值类型-BaseResponse
    神奇的选择器 :focus-within
    妙用 scale 与 transfrom-origin,精准控制动画方向
  • 原文地址:https://www.cnblogs.com/Leekin/p/4589792.html
Copyright © 2011-2022 走看看