gpt4 book ai didi

C++删除指针 vector

转载 作者:太空狗 更新时间:2023-10-29 19:46:40 25 4
gpt4 key购买 nike

这是我的代码:

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

我正在尝试删除指向 vector 的指针以及 vector 内部的所有指针。然而,在我尝试这样做之后,Bar 仍然执行得很好......

最佳答案

它会导致未定义的行为。这意味着任何事情都可能发生。这:

*reinterpret_cast<int*>(0x12345678) = 314159;

也可能有效……那又怎样?

关于C++删除指针 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8659996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com