C++/STL_中的push_back方法与复制数据的问题

来源:互联网 发布:英超进球数据 编辑:程序博客网 时间:2024/06/10 14:56


STL中有push_back 等方法 可以将一个数据放入容器中


在push_back中完成的是值拷贝,而不仅仅是地址的复制。


#include <vector>#include <iostream>using namespace std;typedef struct point{int x;int y;}Point;ostream& operator<<(ostream& output, const Point &a){return output << a.x <<" "<< a.y;}int main(){Point * a = new Point;vector<Point> PointList;a->x = 3;a->y = 4;PointList.push_back(*a);a->x = 4;a->y = 4;PointList.push_back(*a);a->x = 5;a->y = 4;PointList.push_back(*a);delete a;for (vector<Point>::iterator i = PointList.begin(); i != PointList.end(); i++){cout << (*i)<< endl;}return 0;}



这说明完成的不是将a的地址加入到vector,而是将数据整个拷贝了一份加入进去。

当然如果用类(如Point类)构造的容器来说如果有new/malloc分配的空间,要重写复制构造函数才不会出问题。

1 0
原创粉丝点击