c++数组引用一二
来源:互联网 发布:网络机柜报价 编辑:程序博客网 时间:2024/04/30 12:54
本文是关于今天遇到的问题的经验之谈,不成系统,没有娓娓道来,只是留个印象免得日后重蹈覆辙。
C++可以使用数组引用来对数组参数进行安全检查,但是在类的内部使用数组的引用的时候经常会犯这样的问题:
typedef int (&DV3)[3];class directionVector{public:directionVector(DV3 param);DV3 dv;}对,如你所见,directionVector 是个存储向量的类,为了既能对构造参数进行安全检查又图省事儿,向量数据竟然存储在了一个引用里!!结果就是dv是一个对局部变量的引用,而这个局部变量随时可能被清理并被新的数据覆盖,这就像局部变量的指针一样可怕。如下列代码所示,
class directionVector{public:directionVector(DV3 param);DV3 dv;};directionVector::directionVector(DV3 param):dv(param){ }directionVector* newclass(){int intarray[3] = {1,1,1};cout<<intarray<<endl;// 打印intarray地址directionVector *ptr = new directionVector(intarray);return ptr;}int _tmain(int argc, _TCHAR* argv[]){directionVector *ptr = newclass();cout<<ptr->dv<<endl;// 打印ptr->dv的地址getchar();return 0;}
打印结果截图:
为了避免这样的结果,需要在类directionVector中开辟一块空间用来存储向量数据,对类重新进行一下定义:
class directionVector{public:directionVector(DV3 param);DV3 dv;private:int data[3];};directionVector::directionVector(DV3 param):dv(data){dv[0] = param[0];dv[1] = param[1];dv[2] = param[2];}
问题解决了,现在有了一个12字节可以用于安全读取和修改的data数组,但是新的问题也紧随其后,为了存储一个12字节的向量我们却一共耗费了16个字节(dv+data[3]),而且如果类的内部如果有很多类似data的数组,既需要提供安全检查,又需要存储数据的话无疑dv对的空间占用无疑是不小的代价。
dv是为了对参数进行安全检查而出现的衍生品,那么就需要可以对dv下手,将参数安全检查的责任从directionVector剥离开来,重新进行如下定义
// test//#include "stdafx.h"#include <iostream>using namespace std;typedef int (&DV3)[3];class directionVector;class directionVector{public:friend directionVector* newDV(DV3 param);private:directionVector() {}directionVector(DV3 param);private:int data[3];};directionVector::directionVector(DV3 param){data[0] = param[0];data[1] = param[1];data[2] = param[2];}directionVector* newDV(DV3 param){directionVector *ptr = new directionVector(param);return ptr;}int _tmain(int argc, _TCHAR* argv[]){int array[3] = {1,2,3};directionVector *ptr = newDV(array);cout<<sizeof(directionVector)<<endl;getchar();return 0;}
这样一来 directionVector 的构造和参数检查全由newDV(...) 函数全权负责。
,又或者可以直接删掉成员dv,在构造函数中使用param对data直接赋值也可以。
呵呵。我太水了。
结束。
funte
1562165834@qq.com
- c++数组引用一二
- 数组引用(C++)
- c++-引用二维数组
- [C/C++]数组的引用、多维数组
- c++-引用一维数组
- 【C】指针、引用和数组
- [C++]关于数组的引用和引用的数组
- C/C++之感悟一二
- C中数组的另类引用
- C中数组的另类引用
- C#中数组是引用类型
- C语言之指针,数组,引用
- C/C++对数组的引用
- C/C++指针、数组和引用
- 【C++】指针,数组名,引用的区别
- C语言之指针,数组,引用
- C语言通过指针引用数组
- C通过指针引用数组元素
- 特征降维-PCA(Principal Component Analysis)
- Android清除本地数据缓存代码案例 sqlite sharedpref 等等
- Android--数据库升级,插入新字段
- 【索引】字符串
- Android程序怎样禁止横竖屏切换
- c++数组引用一二
- Brief Intro to NSError of Foundation Framework
- Linux下单网卡多vlan多虚拟机
- iphone开发 运行模拟器出现"ARC forbids explicit message send of 'retain' 错误信息
- 【索引】大数
- 标准库 STL :Allocator能做什么?
- maven 配置
- 5.2 PREDICTING PERFORMANCE
- signal_pending