因为设备限制,我现在windows下进行测试,以下代码全部都在vs2013中运行过
下面是例子1:
#include <stdio.h> #include <iostream> #include <memory> #include <vector> using namespace std; class D { public: D() : d(1) {} ~D() { printf("D destruction\n"); } int d; }; void AutoPtrInVec() { vector<auto_ptr<D> > auto_vec; for (int i = 0; i < 10; i++) auto_vec.push_back(auto_ptr<D>(new D)); for (int i = 0; i < 10; i++) printf("auto_vec[%d]->d: %d\n", i, auto_vec[i]->d); } int _tmain(int argc, _TCHAR* argv[]) { AutoPtrInVec(); getchar(); return 0; }
auto_vec[0]->d: 1 auto_vec[1]->d: 1 auto_vec[2]->d: 1 auto_vec[3]->d: 1 auto_vec[4]->d: 1 auto_vec[5]->d: 1 auto_vec[6]->d: 1 auto_vec[7]->d: 1 auto_vec[8]->d: 1 auto_vec[9]->d: 1 D destruction D destruction D destruction D destruction D destruction D destruction D destruction D destruction D destruction D destruction
那么,从以上例子是否就说明auto_ptr可以作为vector的元素吗?答案是否定的,看以下例子:
#include <stdio.h> #include <iostream> #include <memory> #include <vector> using namespace std; class D { public: D() : d(1) {} ~D() { printf("D destruction\n"); } int d; }; void FunAuto(auto_ptr<D> d) { printf("do nothing\n"); } void AutoPtrInVec() { vector<auto_ptr<D> > auto_vec; for (int i = 0; i < 3; i++) auto_vec.push_back(auto_ptr<D>(new D)); for (int i = 0; i < 3; i++) printf("auto_vec[%d].get(): %p\n", i, auto_vec[i].get()); for (int i = 0; i < 3; i++) FunAuto(auto_vec[i]); for (int i = 0; i < 3; i++) printf("auto_vec[%d].get(): %p\n", i, auto_vec[i].get()); printf("\n"); auto_vec.clear(); for (int i = 0; i < 3; i++) auto_vec.push_back(auto_ptr<D>(new D)); for (int i = 0; i < 3; i++) printf("auto_vec[%d].get(): %p\n", i, auto_vec[i].get()); for (int i = 0; i < 3; i++) auto_ptr<D> temp = auto_vec[i]; for (int i = 0; i < 3; i++) printf("auto_vec[%d].get(): %p\n", i, auto_vec[i].get()); } int _tmain(int argc, _TCHAR* argv[]) { AutoPtrInVec(); getchar(); return 0; }
auto_vec[0].get(): 0041C930 auto_vec[1].get(): 0041C9B0 auto_vec[2].get(): 0041C970 do nothing D destruction do nothing D destruction do nothing D destruction auto_vec[0].get(): 00000000 auto_vec[1].get(): 00000000 auto_vec[2].get(): 00000000 auto_vec[0].get(): 0041C930 auto_vec[1].get(): 0041C970 auto_vec[2].get(): 0041C9B0 D destruction D destruction D destruction auto_vec[0].get(): 00000000 auto_vec[1].get(): 00000000 auto_vec[2].get(): 00000000
C++标准如是说:“STL元素必须具备拷贝构造和可赋值……”,很显然从上述过程中看出auto_ptr作为vector的元素明显不能达成这个条件,所以任何情况下最好不要把auto_ptr作为vector的元素,它可能在你调用swap、sort等函数的过程中就默默失效了。