c++中指针变量--learing "c++ primer"

a simple class with a pointer member:

class HasPtr

{

public:

// copy of the values we're given

HasPtr(int *p, int i) : ptr (p), val (i) { }

 

//.....

 

 

 

private:

int *ptr; // pointer member

int val;

};

 

Class that have pointer members and use default synthesized copy control have all the pitfalls of ordinary pointers. In particular, the class itself has no way to avoid dangling pointers.

 

int obj = 0;

HasPtr ptr1 (&obj, 42);

HasPtr ptr2 (ptr1);

 

after the copy, the pointers in ptr1 and ptr2 both address the same object and the int value in each object are the same. However, the int value are distinct and independent, whereas the pointers are intertwined.

 

To conquer the problem, we can define smart pointer classes or valuelike classes.

1. By using pointer classes, we can  import a use count to keep track of how many objects of the class share the same pointer. When the use count goes to zero, the the object is deleted. If we use use count, we must define all three copy-control members: the copy constructor, assignment operator, and the desctructor.

2. valuelike classes. when we copy a valuelike object, we get a new, distinct copy, not a pointer. Changes made to a copy have no effect on the original object. Just like use count, valuelike classes should not use the synthesized copy control.

 

 但是这两种方法好像还是不能满足需求。

第一种方法,解决不了局部变量的问题。

而第二种方法,却又不是指针了。有些问题用起来不方便,比如

class Person

{

....

private:

Person * father;

Person * mother;

};

Person p1;

Person p2 = p1; // 这个时候好像不能用valuelike classes, p1.father 和p2. father就需要是同一个对象的。

 

。。。待解决

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值