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就需要是同一个对象的。
。。。待解决
- c++中指针变量--learing "c++ primer"
- C++Primer——变量、引用、指针
- C++Primer变量
- C++Primer--数组、指针
- 4、C语言中 指向指针变量的指针变量
- C语言中Const指针变量
- C语言中指针变量的初始化
- C 语言中指针变量的运算
- 单片机中C语言指针与变量
- c语言中const修饰指针变量
- c++primer 2/22---变量
- c++primer笔记--2.2变量
- c++primer 2/27----指针
- C++primer 指针学习笔记
- 关于指针(c++primer)
- C++Primer 数组和指针
- C++primer 指针(二)
- C++Primer中 智能指针一例分析
- 博客收集
- 操作必须使用一个可更新的查询;HTTP 500 - 内部服务器错误; 您未被授权查看该页;您不具备使用所提供的凭据查看该目录或页的权限;HTTP 错误 401.3 - 访问被资源 ACL 拒绝
- char、varchar、text和nchar、nvarchar、ntext的区别
- Java 技术是什么?
- 大学生计算机专业毕业生为何纷纷转行
- c++中指针变量--learing "c++ primer"
- sed学习1
- 如何使用C#读取文本文件
- 项目管理--技术民主和管理独裁
- linux 系统下使用C程序实现时钟的函数
- AS3.0中用于网络通信的类总结
- SDRAM芯片的预充电与刷新操作
- TCP checksum offload
- C#中如何产生字母和数字的随机组合