零、小序
vector是C++程序員經常使用的一種序列化容器,可以說C++程序員每天都在使用,vector中可以存放各種類型的數據,使用起來簡單方便。vector用來存放指針這不是一個新鮮事,vector釋放空間也不是新鮮事,那麼從vector中單獨取出來一個指針,這個指針使用完需要單獨釋放空間嗎?你知道嗎?不知道的來看看,知道的繞道吧。
一、先來看一段代碼
1、代碼示例
// TestArray2.cpp : 此文件包含 "main" 函數。程序執行將在此處開始並結束。
//
#include <iostream>
#include <vector>
using namespace std;
class Person
{
public:
int age;
};
int main()
{
vector<Person*> tmpVector;
for (int i=1; i<10; ++i)
{
Person *pPerson = new Person;
pPerson->age = i;
tmpVector.emplace_back(pPerson);
}
Person *tmpPerson = tmpVector.at(0);
if (tmpPerson != nullptr)
{
delete tmpPerson;
tmpPerson = nullptr;
}
for (auto iter=tmpVector.begin(); iter!=tmpVector.end(); ++iter)
{
if (*iter != nullptr)
{
delete (*iter);
(*iter) = nullptr;
}
}
// 清空vector數據並釋放空間
tmpVector.clear();
vector<Person*> tmpSwapVector;
tmpSwapVector.swap(tmpVector);
std::cout << "Hello World!\n";
getchar();
}
2、這段代碼能正常運行嗎
答案:當然是不能的!而且程序會崩潰!原因就是從vector中取出的tmpPerson單獨釋放了空間,導致tmpVector中存儲的第一個指針變成了野指針,tmpPerson和tmpVector[0]指向的是同一塊內存地址,同一塊地址釋放兩次空間肯定會崩潰的!只需要在tmpVector中釋放空間就可以了。
3、運行現象
VS2017下面,可以看到崩潰了,並且自動跳轉到和內存釋放的代碼庫中。
二、正確的示範
下面的代碼中使用條件編譯把有問題的代碼註釋掉了,並加了註釋說明。
// TestArray2.cpp : 此文件包含 "main" 函數。程序執行將在此處開始並結束。
//
#include <iostream>
#include <vector>
using namespace std;
class Person
{
public:
int age;
};
int main()
{
vector<Person*> tmpVector;
for (int i=1; i<10; ++i)
{
Person *pPerson = new Person;
pPerson->age = i;
tmpVector.emplace_back(pPerson);
}
cout << "-------------打印vector中所有指針的地址------------" << endl;
for (auto iter : tmpVector)
{
cout << iter << endl;
}
cout << "-------------打印從vector中取出的指針的地址------------" << endl;
Person *tmpPerson = tmpVector.at(0);
cout << tmpPerson << endl;
#if 0
// 這裏不需要釋放,後面釋放數組中的空間就可以了
// 如果在這裏釋放的話,vector的第一個指針會變成野指針,後面再釋放vector空間時程序會崩潰
if (tmpPerson != nullptr)
{
delete tmpPerson;
tmpPerson = nullptr;
}
#endif
for (auto iter=tmpVector.begin(); iter!=tmpVector.end(); ++iter)
{
if (*iter != nullptr)
{
delete (*iter);
(*iter) = nullptr;
}
}
// 清空vector數據並釋放空間
tmpVector.clear();
vector<Person*> tmpSwapVector;
tmpSwapVector.swap(tmpVector);
std::cout << "Hello World!\n";
getchar();
}
運行結果:
能力有限,如有錯誤,多多指教!原創不易,點贊鼓勵一下吧!