指针与复制构造函数

#指针与复制构造函数

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

using std::cout;
using std::endl;

struct Node
{
    char *name;
    int age;
    Node(char *n=" ",int a=0)
    {
        name = strdup(n);//strdup()在内部调用了malloc()为变量分配内存,不需要使用返回的字符串时,
                       //需要用free()释放相应的内存空间,否则会造成内存泄漏。
        age = a;
    }
    Node(const Node & n)//copy constructor
    {
        name = strdup(n.name); //Allocate memory internally
        age = n.age;
    }
//    Node & operator=(const Node & n)
//    {
//      if(this!=&n)
//      {
//          if(name!=0) free(name);
//          name = strdup(n.name);
//          age = n.age;
//      }
//      return *this;//*this is the object itself
//    }
    ~Node()
    {
        if(name!=0)free(name);//As for a char character, number 0 standard for \0;
    }
};

int main()
{
    cout << "Hello world ! For a long time!" << endl;

    Node node1("A",10), node2(node1), node3 = node1;//<=======call default copy constructor
    strcpy(node1.name, "B");
    node1.age=20;
    cout << "have copy constructor but no operator =:\n" << "node1.name:" << node1.name << "\tnode2.name:" << node2.name << "\tnode3.name:" << node3.name << endl;
    cout << "node1.age:" << node1.age << "\tnode2.age:" << node2.age << "\tnode3.age:" << node3.age << endl;

//    No copy constructor but operator =:
//    node1.name:B    node2.name:B    node3.name:B
//    node1.age:20    node2.age:10    node3.age:10

//    have copy constructor but no operator =:   <====It seems that operator = have no influence........
//    node1.name:B    node2.name:A    node3.name:A
//    node1.age:20    node2.age:10    node3.age:10

//    编译器的默认复制构造函数只是逐个复制,node2.name指针没有指向重新分配内存空间,而是直接将node1.name指针指向的地址复制过去,
//    两个指针指向同一内存!!!因此存在指针的情况必须定义复制构造函数


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值