#学习自用#
自制智能指针
#include<iostream>
#include<string>
#include<memory>
using namespace std;
class entity
{
public:
void demonstr () const
{
cout<<"hello"<<endl;
}
};
class scopedptr
{
private:
entity* m_obj;
public:
scopedptr(entity* const e)
:m_obj(e){}
~scopedptr()
{
delete m_obj;
}
const entity* operator->()const
{
return m_obj;
}
};
void main()
{
const scopedptr e=new entity();//scopedptr e(new entity())
e->demonstr();
cin.get();
}
智能指针要求在超出作用域时被自动删除,scopedptr实现了这一功能,接下来做几点说明:1) const scopedptr e=new entity() 这句等效于 scopedptr e(new entity()) 是将 new entity 返回的指针作为构造函数的输入,并不是隐式转换!!2)如果没有箭头操作符的重载,那么 e 是没有办法像指针那样通过箭头符号去调用方法,因为 e 本质上是 scopedptr 类的实例。3)因为操作符重载返回值为 const entity,如果方法不加const是无法调用的。
计算偏移量
#include<iostream>
using namespace std;
struct vector3
{
float x,y,z;
};
int main()
{
int offset1=(int)&((vector3*)0)->x;
cout<<offset1<<endl;
int offset2=(int)&((vector3*)0)->y;
cout<<offset2<<endl;
cin.get();
}
(vector*)0 是将0地址强转为vector类型指针,&((vector*)0)->x是取出这个0指针下x的地址也就是偏移量。
Vector
vector本质上是一个动态数组而不是向量,vector使用new和delete来管理内存,这两种操作是自动的,使用时可以设定一个大小进行初始化,但如果是要创建确定大小的数组用普通的数组定义更佳,因为vector效率较低,你使用初始设定了一个大小的 vector ,但是输入的数据超过设定的大小时,vector会创建一个比之前数组更大的新数组,并把所有东西复制到新数组,然后删除旧数组。其定义为vector<类型名>变量名(元素个数),(元素个数)这一项可以省略。
#include<iostream>
#include<vector>
using namespace std;
struct Vertex3
{
float x,y,z;
Vertex3(float x,float y,float z)//VS2010不支持初始化列表的语法,只能手动使用构造函数
:x(x),y(y),z(z){}
};
std::ostream& operator<<(std::ostream& stream, const Vertex3&v)//方便打印
{
stream<<v.x<<","<<v.y<<","<<v.z;
return stream;
}
int main()
{
vector<Vertex3>vertices;
vertices.push_back(Vertex3(1,2,3));
vertices.push_back(Vertex3(4,5,6));
for(int i=0;i<vertices.size();i++)
cout<<vertices[i]<<endl;
vertices.erase(vertices.begin()+1);//删除第二个元素,erase的参数要求输入迭代器所以不能直接输入整数比如2之类的
for(int i=0;i<vertices.size();i++)
cout<<vertices[i]<<endl;
cin.get();
}
这里进行一些说明,push_back() 是添加元素,如果是使用的版本稍微新一点的vs,Vertex3的构造函数可以删除,添加元素的语句可以简化为 vertices.push_back({1,2,3}); vs2010不支持初始化列表的语法,说真的,要不是我c盘容量告急,真的不想用vs2010。重载了左移操作符方便打印,记得多用引用,避免传参时发生数据复制,拖慢程序运行速度。vertices.size()可返回vertices数组中元素个数。erase可删除对应位置的元素,但是erase的参数要求输入迭代器所以不能直接输入整数比如2之类的。