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

来源:互联网 发布:类似于forest的软件 编辑:程序博客网 时间:2024/04/30 04:59

a simple class with a pointer member:

classHasPtr

{

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就需要是同一个对象的。

 

。。。待解决

 

 

原创粉丝点击