[c++]代理对象模式
2016-07-24 17:21
525 查看
代理对象
#include <iostream> #include <vector> using namespace std; class Vehicle { public: Vehicle() {} virtual string getName() = 0; }; class Car : public Vehicle { public: Car() { name = "car"; } virtual string getName() { return name; } ~Car() { cout << "delete" << endl; } private: string name; }; class Bike : public Vehicle { public: Bike() {} virtual string getName() { return "bike"; } private: string name; }; void wrong_code(vector<Vehicle *> &parkinglot) { Car c; cout << &c << endl; parkinglot[0] = &c; //将c插入到parkinglot内 cout << &(*parkinglot[0]) << endl; } int main() { vector<Vehicle *> parkinglot(1); wrong_code(parkinglot); cout << parkinglot[0]->getName() << endl; // Oops!!parkinglot内存的地址指向了一块被销毁的内存 cout << &(*parkinglot[0]) << endl; return 0; }
0x7fff5fbff6d8
0x7fff5fbff6d8
delete
0x7fff5fbff6d8 0x7fff5fbff6d8 delete 乱码。。。。 0x7fff5fbff6d8
在这种情况下会出现因为临时对象在生命周期结束之后,对象上的内存被释放,所以访问它的数据就会出现不可预计的结果。
在这种大前提下,代理类就顺势而生了.
顾名思义,代理类就是指某个基类以及其子类的代理,其功能是使之能在容器中也表现出多态性.而没有动态内存管理的烦恼.
现在定义Vehicle以及子类的代理类VehicleSurrogate.
#include <iostream> #include <vector> using namespace std; class Vehicle { public: Vehicle() {} virtual string getName() = 0; virtual Vehicle *copy() const = 0; virtual ~Vehicle() {} //虚析构函数是为了支持多态.但是本例中并不需要. private: }; class Car : public Vehicle { public: Car() { name = "car"; } virtual string getName() { return name; } virtual Vehicle *copy() const { return new Car; } virtual ~Car() {} private: string name; }; class Bike : public Vehicle { public: Bike() { name = "bike"; } virtual string getName() { return name; } virtual Vehicle *copy() const { return new Bike; } virtual ~Bike() {} private: string name; }; class VehicleSurrogate { public: VehicleSurrogate() : p(0) {} VehicleSurrogate(const Vehicle &v) : p(v.copy()) {} VehicleSurrogate(const VehicleSurrogate &vs) : p(vs.p ? vs.p->copy() : 0) {} VehicleSurrogate &operator=(const VehicleSurrogate &vs) { if (this != &vs) //在删除p之前一定得记得判断vs和this是不是同一个,否则会有问题 { delete p; p = vs.p->copy(); } return *this; } string getName() { return p->getName(); } ~VehicleSurrogate() { delete p; } private: Vehicle *p; }; void right_code(vector<VehicleSurrogate> &parkinglot) { Car c; parkinglot.push_back(c); } int main() { vector<VehicleSurrogate> parkinglot; right_code(parkinglot); cout << parkinglot[0].getName() << endl; return 0; }
car
所以,这种代理对象的模式实际上就是对对象的封装,同时处理他们对他们进行资源管理,从而防止指针对象指向未被析构的对象地址,已经内存泄露的问题。
示例来自
相关文章推荐
- 【C++ 与 STL】双端队列:deque
- Leetcode 226. Invert Binary Tree (Easy) (cpp)
- 【C++ 与 STL】栈:stack
- 多态(Polymorphism)
- 【C++ 与 STL】映射:map
- 【C++ 与 STL】集合:set
- Leetcode 107. Binary Tree Level Order Traversal II (Easy) (cpp)
- 【C++ 与 STL】不定长数组:vector
- 【读书笔记】摘自Google开源项目风格指南-C++风格指南
- 实现自己的C++ STL--vector容器
- C语言中二级指针的作用
- C++设计模式——建造者模式
- C语言真正的编译过程
- 大话设计模式16----状态模式
- Xcode 修改 c++ 模板文件
- 正则表达式规则及C语言测试代码
- c指针解析
- C++中的RAII机制
- C语言数组
- C++中的<limits.h>和<climits>(C++基本数据类型的最值)