C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C删除指针的向量大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的代码

#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;

也可以工作……那又怎样?

大佬总结

以上是大佬教程为你收集整理的C删除指针的向量全部内容,希望文章能够帮你解决C删除指针的向量所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。