C删除指针的向量
发布时间:2020-12-16 10:20:56 所属栏目:百科 来源:网络整理
导读:这是我的代码: #include vector#include stdio.h#include iostreamusing namespace std;class Foo {public: Foo() { } ~Foo() { } void Bar() { cout "bar" endl; }};template class Tvoid deleteVectorOfPointers( T * inVectorOfPointers ){ typename T::
这是我的代码:
#include <vector> #include <stdio.h> #include <iostream> using namespace std; class Foo { public: Foo() { } ~Foo() { } void Bar() { cout << "bar" << endl; } }; template <class T> void deleteVectorOfPointers( T * inVectorOfPointers ) { typename T::iterator i; for ( i = inVectorOfPointers->begin() ; i < inVectorOfPointers->end(); i++ ) { delete * i; } delete inVectorOfPointers; } int main() { //create pointer to a vector of pointers to foo vector<Foo*>* pMyVec = new vector<Foo*>(); //create a pointer to foo Foo* pMyFoo = new Foo(); //add new foo pointer to pMyVec pMyVec->push_back(pMyFoo); //call Bar on 0th Foo element of pMyVec pMyVec->at(0)->Bar(); //attempt to delete the pointers inside the vector and the vector itself deleteVectorOfPointers(pMyVec); //call Bar on 0th Foo element of pMyVec pMyVec->at(0)->Bar(); //call Bar directly from the pointer created in this scope pMyFoo->Bar(); return 0; } 我试图删除一个指向矢量的指针以及矢量内的所有指针.但是,在我尝试这样做之后,Bar仍然执行得很好…… 解决方法
它会导致未定义的行为.这意味着任何事情都可能发生.这个:
*reinterpret_cast<int*>(0x12345678) = 314159; 也可以工作……那又怎样? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |